uWSGI is a Web Server Gateway Interface that sits between your application and web server. In our case we're going to use it to run our Flask application. For this project we want requests to hit Nginx which will then internally proxy the requests to our uWSGI which will return pages from our Flask application. I know it sounds complicated but it's actually pretty straightforward.

This project assumes that you have Nginx already installed.

First let's install uWSGI:

sudo apt-get install build-essential python-dev python-pip
sudo pip install uwsgi

Next, let's install Flask:

sudo pip install Flask

uWSGI has it's own protocol used for comunicating with upstream servers and if you have a recent version of Nginx (>=0.8.40) there is native support for it. Navigate to /etc/nginx/ and create a uwsgi_params file:

uwsgi_param QUERY_STRING $query_string;
uwsgi_param REQUEST_METHOD $request_method;
uwsgi_param CONTENT_TYPE $content_type;
uwsgi_param CONTENT_LENGTH $content_length;
uwsgi_param REQUEST_URI $request_uri;
uwsgi_param PATH_INFO $document_uri;
uwsgi_param DOCUMENT_ROOT $document_root;
uwsgi_param SERVER_PROTOCOL $server_protocol;
uwsgi_param REMOTE_ADDR $remote_addr;
uwsgi_param REMOTE_PORT $remote_port;
uwsgi_param SERVER_ADDR $server_addr;
uwsgi_param SERVER_PORT $server_port;
uwsgi_param SERVER_NAME $server_name;

Next, let's add a location directive the Nginx sites-available file so that it knows how to pass requests to uWSGI:

location / {
          gzip on;
          include uwsgi_params;
          uwsgi_pass 127.0.0.1:6267
  }

Let's break this down a bit:

  • location / - This means that all requests to your website root will be passed to the uWSGI application.
  • gzip on; - Nginx will gzip compress all of the files sent out by your application.
  • include uwsgi_params; - Tells Nginx to include the uwsgi_params file so it can use the uwsgi protocol.
  • uwsgi_pass 127.0.0.1:6267 - the IP and port to route requests to using TCP.

Now we can create a simple flask application. Create a file called hello.py in the folder where you want to application to reside:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

Now, let's fire up our uWSGI server to run this application:

uwsgi --http :6267 --wsgi-file hello.py

Be sure to specify the same port number as the one used in the sites-available location directive. Now let's restart Nginx:

sudo nginx -s reload

Navigate to your webpage and you should the words "Hello World!" on the page.

Comments or Questions? Send me an email or hit me up on twitter.