nginx + gunicorn + flask + systemd

May 25th, 2023

A cheat-sheet on how to run a flask application within gunicorn as a wsgi-server under the systemd control and integrate it with nginx.

Create a virtual environment. Prerequisite (ubuntu):

apt install python3-venv

Installation of gunicorn and flask:

mkdir <application_dir>
cd <application_dir>/
python3 -m venv .
. ./bin/activate
pip install gunicorn
pip install flask

Create an application, e.g. hello.py:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return "hello"

Monitoring via systemd:

/etc/systemd/system/gunicorn.service

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
Type=notify
User=...
Group=...
WorkingDirectory=<application_dir>
ExecStart=<application_dir>/bin/gunicorn 'hello:app'
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true

[Install]
WantedBy=multi-user.target

/etc/systemd/system/gunicorn.socket:

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock
SocketUser=www-data

[Install]
WantedBy=sockets.target

Activate and start the service:

systemctl enable --now gunicorn.socket

Test the application (unix socket - gunicorn - flask):

curl --unix-socket /run/gunicorn.sock http

Integrate it with nginx:

http {

    upstream flask {
        server unix:/run/gunicorn.sock;
    }

}

server {

    location /... {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://flask/;

    }

}

Details on the proxy_pass:


Next: TK-Star TK905-4G GPS Tracker

Previous: InfluxDB Corrupted Data

Main Menu