Running a Python Flask application under Apache

When developing a Flask application, you normally run it from the terminal using

flask run

or in the code

app.run()

But when the app is ready, how do you install it under an Apache Webserver?

For basics about setting up Virtual Hosts in Apache I recommend https://blogg.fsh.se/2018/04/18/adding-a-new-website-under-apache/ and https://blogg.fsh.se/2021/10/14/installing-a-certificate-using-letsencrypt-on-a-ubuntu-server-with-apache/

The rest of this article assumes that you are comfortable with setting up Virtual Hosts under Apache.

Python applications are run under a protocol called WSGI (Web Server Gateway Interface). WSGI acts as a interface between the web server and a python appliaction.

You must first install the Apache WSGI module (wsgi_mod) unless it already is installed:

$ sudo apt-get update
$ sudo apt-get install apache2 apache2-utils libexpat1 ssl-cert python

followed by:

$ sudo apt-get install libapache2-mod-wsgi-py3

(Be careful to install the python3 version, indicated by -py3)

and then restart Apache

sudo systemctl restart apache2

Assuming that you have your Python Flask application under /home/peter/myserver, and that the file is called app.py, you should create another file app.wsgi containing:

#! /usr/bin/python3.6
import logging
import sys
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, '/home/peter/myserver')

# load your app...
from app import app as application
application.secret_key = 'anything you wish'

Then you must add this to your Virtual host:

WSGIScriptAlias / /home/peter/myserver/app.wsgi

# set permissions as per apache2.conf file
Options FollowSymLinks
AllowOverride None
Require all granted

Now all HTTPS calls to your domain-name will be routed to your Flask application.

Steps that are not described in this article, but also necessary are:

  • Setting up a DNS entry mapping domain name to an IP address
  • Having a ServerName in your Virtual Host definition that maps to the domain name
  • Setting up Letsencrypt certificates using “certbot”.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.