Skip to content
Advertisement

Creating Apache web server on Ubuntu with Connexion/Flask and public IP address

I am trying to run a simple python server with REST API and Connexion/Flask built in on a remote Linux server (binding to the server public IP address) using Apache. (Server is running Ubuntu 16.04.5 LTS, python code was written in Python 3.7)

Here are some files for the server implementation:

server.py:

import connexion
app = connexion.App(__name__, specification_dir='./')
app.add_api('swagger.yml')

if __name__ == "__main__":
    app.run(host='127.0.0.1', port=5000, debug=True)

swagger.yml: Specifications for the REST API, I have tested it by running on the localhost and it’s working properly. (The base path is /api)

opertations.py: Functions for the API depending on the response

My goal is to run the server on a remote Linux server that anyone who knows the public IP address of the server, they will be able to call the API. For example, if the public IP address is xxx.xx.xx.xxx, then users should be able to call the following URL to retrieve the data:

http://xxx.xx.xx.xxx:<port>/api/<operation_name>?<query_parameters>

So far, I was able to call the API (that was running on the localhost on the server) from the client side with SSH port forwarding as well as ngrok (they provide tunnels to the server localhost), but these are not what I want.

I’m new to creating my own web servers and I’ve been looking into Apache and how it works with VirtualHosts etc. but I couldn’t find how exactly to set it up so that it binds the python server to the public IP address of the Linux server.

Advertisement

Answer

The best way to do this is using mod_wsgi from in apache web server

Example:

The flask app is in /var/www/api/app.py

Apache configuration (/etc/apache2/sites-enabled/500-api.conf)

WSGIDaemonProcess app threads=5 home=/var/www/api/
 WSGIScriptAlias /api /var/www/api/app.wsgi

 <directory /var/www/api/>
 WSGIProcessGroup app
 WSGIApplicationGroup %{GLOBAL}
 WSGIScriptReloading On
 Order deny,allow
 Allow from all
</directory>

WSGI File – Calling your flask app (/var/www/api/app.wsgi)

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
sys.path.append('/var/www/api')
from app import app as application
Advertisement