Serve Flask app with apache and wsgi on Ubuntu 20

  1. install Apache and WSGI
    sudo apt install apache2 libapache2-mod-wsgi-py3 python3-pip python3-virtualenv
    sudo pip3 install flask (skip this if you are planning to setup venv)
  2. enableĀ mod_wsgi
    sudo a2enmod wsgi
  3. create files as below (the __init__.py and wsgi file are mandatory)

4. create apache wsgi conf file /etc/apache2/sites-available/flaskhelloworldsite.com.conf
and enable it: $ sudo a2ensite flaskhelloworldsite.com.conf

<VirtualHost *:80>
    ServerAdmin webmaster@flaskhelloworldsite.com
    ServerName 192.168.0.51
    ServerAlias flaskhelloworldsite.com
    ErrorLog /var/www/flaskhelloworldsite.com/logs/error.log
    CustomLog /var/www/flaskhelloworldsite.com/logs/access.log combined

    WSGIDaemonProcess helloworldapp user=www-data group=www-data threads=5
    WSGIProcessGroup helloworldapp
    WSGIScriptAlias / /var/www/FLASKAPPS/helloworldapp/helloworldapp.wsgi
    <Directory /var/www/FLASKAPPS/helloworldapp>
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

5. create log directory
$ sudo mkdir -p /var/www/flaskhelloworldsite.com/logs
$ sudo chown -R www-data:www-data flaskhelloworldsite.com

6. restart apache and verify the app
systemctl restart apache2
then you can open http://192.168.0.51/

NOTE: if you want use python virtual env, we can setup venv in /var/www/FLASKAPPS:
virtualenv venv
source venv/bin/activate
pip install flask

then update WSGIDaemonProcess in /etc/apache2/sites-available/flaskhelloworldsite.com.conf with python-home:
WSGIDaemonProcess helloworldapp user=www-data group=www-data threads=5 python-home=/var/www/FLASKAPPS/venv

Leave a Reply

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