Blog archives

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:


[uwsgi]
chdir = /var/www/example.com
base = /var/www/example.com
socket = /var/www/example.com/%n.sock
logto = /var/log/uwsgi/%n.log
module = mymodule
chmod-socket = 666

There should be a `mymodule.py` 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 `server.py` 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/example.com/logs/error.log;
    access_log /var/www/example.com/logs/access.log;

    server_name example.com;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/var/www/example.com/uwsgi.sock;
    }
}

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]
respawn

exec uwsgi /var/www/example.com/uwsgi.ini

Then either reboot your system or:


sudo service nginx reload
sudo uwsgi /var/www/example.com/uwsgi.ini &

And Bob should be your uncle.

Add a comment

1 comment