[Python] How to Serve Flask Application with uWSGI and Nginx

As python Flask library has a built-in web server, there shouldn't be a problem to serve a web application by just executing the python script while developing or testing. However, when we are deploying an app for real service, it is better to use a web server such as Nginx and Apache considering the performance on live servers. In addition, we use uWSGI to use the web server. To be specific, if uWSGI executes the python application locally and Nginx communicates with the external users, uWSGI communicates with Nginx to serve the python app.

Following are the steps to integrate uWSGI with Nginx

1. Install nginx and python uwsgi plugin
sudo apt-get install nginx
sudo apt-get install uwsgi-plugin-python

2. Install python library uwsgi.
sudo pip install uwsgi

3. Open uwsgi.ini and save the configuration.
sudo nano /etc/uwsgi/apps-enabled/uwsgi.ini
[uwsgi]
chdir=/home/hama/project
uid=root
gid=root
virtualenv=/home/hama/project/venv
chmod-socket=666
callable=app
module=test_main
socket=/tmp/uwsgi.sock
enable-threads=true
threads=10

- chdir: absolute directory of the web service
- virtualenv: (optional) path to the virtual environment in case you're using it
- callable: variable name of the app
- module: name of the python file (e.g. test_main.py -> test_main )
- enable-threads: (optional) if you want to use threads
- threads: (optional) number of threads in case you want to use threads

4. Change the permission of uwsgi.ini file.
sudo chmod 666 /etc/uwsgi/apps-enabled/uwsgi.ini


5. Edit ngninx configuration file as following.
sudo nano /etc/nginx/sites-available/default
server {

    listen 80;                                           
    server_name 127.0.0.1;

    location / {
        try_files $uri @uwsgi;
    }

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

7. Restart nginx and uwsgi.
sudo service nginx restart
sudo service uwsgi restart

If you need to troubleshoot, check logs in the following directory.

sudo nano /var/log/uwsgi/app/uwsgi.log

Comments