Running a Python Flask app with nginx using uWSGI

1 comment

It took me ages to figure out how to run a regular Python Flask app on an Ubuntu installation ‘in production’. I thought it would be as simple as with PHP: simply copy some files over to /var/www/whatever, create a nginx config file. service nginx reload, and it works.

Except that it doesn’t. Python is a bit more complicated. This blog post simply indicates what i did to ‘get things done’, it can probably be done much easier and simpler, so if you think these steps could be improved, please leave a comment.

Here’s roughly what needs to be done. I expect that you’ve already got a few things up and running:

Okay, so here’s what you need to do.

Your app should have a `uwsgi.ini` file that looks like this:

chdir = /var/www/
base = /var/www/
socket = /var/www/
logto = /var/log/uwsgi/%n.log
module = mymodule
chmod-socket = 666

There should be a `` file in the same directory that sets up proper paths:

import sys, os
PATH = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, PATH)

from server import create_app
application = create_app()

And in `` you have this:

app = Flask(__name__)

def create_app()
    return app

Your nginx site configuration looks like this:

server {
    listen 80;

    error_log  /var/www/;
    access_log /var/www/;


    location / {
        include uwsgi_params;
        uwsgi_pass unix:/var/www/;

To make sure stuff is automatically run, here’s a configuration file that needs to be placed in /etc/init/uwsgi.conf

description "uwsgi instance"
start on runlevel [2345]
stop on runlevel [06]

exec uwsgi /var/www/

Then either reboot your system or:

sudo service nginx reload
sudo uwsgi /var/www/ &

And Bob should be your uncle.

Add a comment

1 comment