Read'n'Code - Flaviu Simihaian's Blog

Deploying Flask With Nginx

The Flask docs for this take you 80% of the way there.

Basically, we need uWSGI to create a UNIX socket, which nginx can route requests to as they come in.

First, let’s make sure uWSGI runs independent of nginx.

The docs tell us to write this:

1
uwsgi -s /tmp/uwsgi.sock -w myapp:app

There’s two problems with this:

First, you may get some error that it doesn’t find flask if you are using a virtual environment (which you should).

Second, nginx may not be able to read the file later if the permissions don’t let it.

So I had to adapt it to this:

1
uwsgi -s /tmp/uwsgi.sock -w flask_file_name:app -H /path/to/virtual/env --chmod-socket 666

Now, install nginx with apt-get install nginx. Change the /etc/nginx/sites-available/default to read:

1
2
3
4
5
6
7
8
9
server {
    listen       80;
    server_name  _;
    location / { try_files $uri @yourapplication; }
    location @yourapplication {
      include uwsgi_params;
      uwsgi_pass unix:/tmp/uwsgi.sock;
    }
}

Now symlink the file above to the enabled one, because that’s how nginx works:

1
ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default

Start nginx with ‘/etc/init.c/nginx restart’

Go to a browser and try it out. Yay!

But what if you want to restart the server? nginx will restart, but your uWSGI will not. We’ll use supervisord for that.

1
apt-get install supervisor

We need to set up the /etc/supervisord.conf to tell supervisor what to do:

Now, kill your supervisor, start it again, and your Flask app be running ad infinitum.

1
2
3
ps -A | grep supervisor
kill <id>
sudo supervisord -c /etc/supervisord.conf

Here’s another supervisor sample config file to get you inspired.

Hope this helps.

Comments

Fork Flaviu on GitHub