Things I did

Serve a flask app with gunicorn and nginx

Categories: HowTo
Tags: server flask

I build myself a small flask app to store my cooking recipe collection. To make this app run on my server I had to create a systemd service script and also setup up the nginx config.

The systemd file should be in /etc/systemd/system/$servicename.service:

[Unit]
Description=Gunicorn instance to serve application
After=network.target

[Service]
User=http
Group=http
WorkingDirectory=$folder_with_the_flask_app
ExecStart=$folder_for_the_domain/.venv/bin/gunicorn --bind 127.0.0.1:8000 cookbook:create_app()
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true

[Install]
WantedBy=multi-user.target

The basic nginx config should look like this:

   server {
        listen 80;
        # listen 443 ssl;
        # listen [::]:443 ssl;
        http2 on;
        server_name $used_domain;

        location / {
                proxy_pass http://127.0.0.1:8000/;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header X-Forwarded-Host $host;
                proxy_set_header X-Forwarded-Prefix /;
        }

Don’t forget to create a SSL certificate and also activate it.

A virtual environment needs to be set up for gunicorn to run in:

    cd app-folder
    python -m venv .venv
    . .venv/bin/activate
    pip install . 
    pip install gunicorn

Categories