Deploy Flask & Python3 on Apache2 & Ubuntu

Deploy Flask, a Python 3 microframework, on Apache web server on Ubuntu.
Then you can write your own web pages in Python.

Flask is a very simple framework for writing server side applications with Python. This article shows how to deploy Flask the way it’s installed on a public server.

We use modern and well established tools: Python 3, Apache 2.4 and mod_wsgi. All applications are available from official repositories on since Ubuntu 14.04, except vagrant and virtualbox that are only used for virtualizing the test environment. All of them are Free software.This tutorial builds the system in small, separately testable steps.
To follow this article, you should be fluent with the command line interface, sudo, sudoedit, reading logs, programming Python and controlling daemons such as Apache.

Test Environment

You can do this on any server, but I tested this tutorial with Vagrant 1.8.1. If you want to test it the same way

$ mkdir terosflask/ && cd terosflask/
$ vagrant init ubuntu/trusty32
$ vagrant up
$ vagrant ssh

If you have problems running Vagrant on Ubuntu 14.04 host, see my fix.

Hello Flask World

Install Python3 versions of required tools & libraries

$ sudo apt-get update
$ sudo apt-get -y install python3 ipython3 python3-flask curl

For testing purposes, we create a sample project in “vagrant” home directory. This is the default user with vagrant visualization tool.

$ pwd
/home/vagrant/
$ mkdir flask/ && cd flask/
$ nano moi.py

Write Hello World with ‘nano moi.py’ and save it (ctrl-X y enter). Yes, it’s nice and simple.

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
 return 'See you in TeroKarvinen.com!\n\n'
if __name__ == '__main__':
 app.run(host='0.0.0.0', port=5000)

Try with Development Server

Development server is not suitable for public use. You must still deploy your program on Apache2+mod_wsgi when you publish it.
Just run your moi.py script like any other Python3 program to start the development server.

$ python3 moi.py
* Running on http://0.0.0.0:5000/

Test it on another terminal (on the same host)

$ curl http://localhost:5000
See you in TeroKarvinen.com!

Did you download the text from the web server? Well done, you have written your first Flask program. And you have run it on test server, and downloaded the first page. You can kill your development server (“python3 moi.py”) with ctrl-C.
Now, let’s deploy your first program on a real server.

Install Apache2 Web Server

Install Apache2.

$ sudo apt-get -y install apache2

Once it’s done, try browsing the default web page.

$ curl -s http://localhost/|grep -i title
<title>Apache2 Ubuntu Default Page: It works</title>

You should see the text of the default website. If you want to see the whole welcome page, just run “curl localhost”.

Mod_wsgi for running Python3 with Apache

Install mod_wsgi, the module for running your Python code from Apache. You must use python3 version of mod_wsgi. If you have installed the old Python 2 version of mod_wsgi module, you must remove it first with “sudo apt-get -y remove libapache2-mod-wsgi”.

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

Virtualhost for Your New Program

Virtualhosts are the sites Apache2 is serving. Create a new available virtualhost

$ sudoedit /etc/apache2/sites-available/moi.conf

You probably don’t have nameserver configured for “ServerName tero.example.com”, but we’ll later make this the default website by disabling other virtualhosts.
In this test setup with Vagrant, the Python code will run as user “vagrant”. In a real production system, it’s a good idea to create a non-login user just for running the code.
Notice the new syntax “Require all granted” instead of the obsolete “Order allow,deny”, “Allow from all”. If you mistakenly use the obsolete syntax, you get “‘AH01630: client denied by server configuration” in the logs. The “Require all granted” is used since Apache 2.4.
“WSGIScriptReloading On” allows updating your flask program without restarting apache, and thus, without sudo. When you modify your program (Python code, HTML…), you can load new code with ‘touch /home/vagrant/flask/moi.wsgi’.

## /etc/apache2/sites-available/moi.conf
<VirtualHost *>
 ServerName tero.example.com
 WSGIDaemonProcess moi user=vagrant group=vagrant threads=5
 WSGIScriptAlias / /home/vagrant/flask/moi.wsgi
<Directory /home/vagrant/flask/>
 WSGIProcessGroup moi
 WSGIApplicationGroup %{GLOBAL}
 WSGIScriptReloading On
 Require all granted
</Directory>
</VirtualHost>

Let’s make this moi.conf the default. Disable all other virtualhosts, and enable only moi.conf.

$ sudo a2dissite 000-default.conf
$ sudo a2ensite moi.conf
$ sudo service apache2 restart

The modifications are only enabled after you restart Apache daemon. To verify that moi.conf is the only virtualhost, you can ‘ls /etc/apache2/sites-enabled/’ and see that “moi.conf” is the only symlink there.
Test your new site and to see – the error.

$ curl -s http://localhost/|grep title
<title>404 Not Found</title>

It gives you the 404. Why? We haven’t created the moi.wsgi script yet. From the error message you can see that your virtualhost changes have an effect on the system. Let’s create moi.wsgi next.

Your Own moi.wsgi Script

To run the Python program, you’ll need a WSGI script.

$ cd /home/vagrant/flask
$ nano moi.wsgi

Notice how this script makes sure that it’s run with Python version 3.To save, ctrl-x y enter.

import sys
if sys.version_info[0]<3:       # require python3
 raise Exception("Python3 required! Current (wrong) version: '%s'" % sys.version_info)
sys.path.insert(0, '/home/vagrant/flask/')
from moi import app as application

Enjoy your page

Restart the web server to load your modifications

$ sudo service apache2 restart

And try it out

$ curl localhost
See you in TeroKarvinen.com!

Well done!
Still sceptical? Let’s see that it’s reallly served by Apache (instead of the built-in development server):

$ curl -sI localhost|grep Server
Server: Apache/2.4.7 (Ubuntu)

If you want to see that it can serve a lot of requests (and you know how to do load testing safely), you can try “ab -n 100 -c 100 http://localhost/”, but be careful to point stress testing tools only to hosts you own.

What Next?

Well done! What Python web apps are you coding next?
If you want to see how Flask is used with NoSQL server ElasticSearch, see StackHay.com.

See also

Flask homepage
Flask Documentation 0.10: mod_wsgi (Apache)
Apache 2 Documentation: Upgrading to 2.4 from 2.2: Access Control
Updates: Fixed HTML, linked StackHay. Tested on a fresh host and made minor fixes. More updates: Added WSGIScriptReloading, tested again.

Posted in Uncategorized | Tagged , , , , , , , , , , , , , , | 13 Comments

13 Responses to Deploy Flask & Python3 on Apache2 & Ubuntu

  1. Nico says:

    I used a lot of this to help me setup a WSGI type install for a Flask REST implementation. It runs in a virtual environment as well.
    The examples and mini tutorial is at GitHub.
    I hope that can help some other people as well.

  2. Thanks for linking my article.
    Some points on your github article https://github.com/nicc777/flask-webservice-wsgi-python3-demo : I would use sudo, and only for the commands that absolutely require it (principle of minimum privilege). It’s dangerous (and unnecessary) to log in as root and run client commands with too high privileges. I would put homepages to some users home directory, and create a new project user with no ability to log in if needed.

  3. On Ubuntu 16.04, you might need to enable the mod_wsgi module:

    $ sudo a2enmod wsgi
    $ sudo service apache2 restart

    This also fixes the error messages: “AH00526: Syntax error on line 4 of /etc/apache2/sites-enabled/moi.conf” and “Invalid command ‘WSGIDaemonProcess’, perhaps misspelled or defined by a module not included in the server configuration”.

  4. NiceDay says:

    I want to ask about Flask app, can I use it on Windows? if yes, how?
    Thanks.

  5. Windows is not a very good environment for a web server, so I would use Linux.
    Also, when you actually create something and want to serve real life customers, how much is the Windows stack going to cost? It’s not just that it can eat your margins, but it’s hard to estimate the costs beforehand.

  6. YOOGYOUNGYOON says:

    Hi.Tero Karvinen
    “mod_wsgi for running Python3 with Apache.”post helped me solve my dizzy problem !
    Thank you so much.

  7. Sherin says:

    Hi Tero,
    I followed your doc and getting “import error, flask is not installed”. Would you give some suggestions?

  8. Nikolai Kleiman says:

    Followed the guide and worked almost without a problems. Need to enable the mod_wsgi module:
    $ sudo a2enmod wsgi
    $ sudo service apache2 restart
    And don’t use slash in the name of Python or WSGI script – I did :p

  9. One option is having Flask for your version of Python. For Python 3, you need python3-flask.

  10. Getting 404 and the wsgi file exist, any ideas?

  11. Ok found my mistake. For those wondering. If you get a 404 or permission error, it’s likely you are using apache 2.4+
    Require all granted
    it’s “Require all granted” in 2.4+. My Django app is running perfectly with this now.

  12. Thanks for sharing the answer with us, William!

  13. mihai says:

    This is the first tutorial i found that worked for me. I just needed to deploy a flask app using wsgi without any virtualenv crap. Your virtualhost config is the first one that works perfectly: no 403, 500 etc