Kensuke Kousaka's Blog

Notes for Developing Software, Service.

Build environment to run Flask application as production using uWSGI + nginx

Previously posted articles related to Flask, to run program by following command.

$ python app.py

Run Flask application directly, and receive request from client without any middleware. This way is for debugging app while developing phase, not for running app as product.

This article describes how to prepare production level app running environment, using uWSGI which works on mediating between Python Web application and Web server like nginx. Receive request by nginx from client and transfer it to Python Web application through uWSGI.

Introduce uWSGI

To install uWSGI environment, run following command.

# pacman -S uwsgi uwsgi-plugin-python

Configure uWSGI

After installing uWSGI, you need to configure uWSGI and nginx before using uWSGI as mediator.

Create configuration file for uWSGI

Create uWSGI configuration file that name like helloflask.ini and put it to same directory as python script. After created, edit it by following.

[uwsgi]
plugins=python
module=app
callable=app
master=true
processes=1
socket=/tmp/uwsgi.sock
chmod-socket=666
vacuum=true
die-on-term=true

Configure to use previously installed uwsgi-plugin-python at plugins=python.

Modify app.py

To use uWSGI, you may need to modify Flask application. If you specify IP address, port number, or some flags like threadding at run() method, remove it.

Configure nginx

Edit nginx.conf by following.

  • Specify user as: user http http;
  • Append include /etc/nginx/site-enabled/*.conf at above http/server block

After editting, run following command to make two directories for saving site configurations.

# mkdir /etc/nginx/site-enabled /etc/nginx/site-available

These directories are for saving site configurations. Put site configurations into site-available directory, and create it's link into site-enabled you want to enable.

Create nginx configuration file for Flask application that working with uWSGI under site-available directory, file name as helloflask.conf.

Edit helloflask.conf by following.

server {
    listen 80;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:///tmp/uwsgi.sock;
    }
}

After editting, create it's link into site-enabled and reload nginx by running following commands.

# ln -s /etc/nginx/site-available/helloflask.conf /etc/nginx/site-enabled/helloflask.conf
# systemctl reload nginx

Configuration has been completed.

Run following command to start Flask application and access through Web browser to check working correctly.

$ uwsgi --ini helloflask.ini