Docs / Programming & Development / Deploying a Flask Application with Gunicorn and Nginx

Deploying a Flask Application with Gunicorn and Nginx

By Admin · Feb 25, 2026 · Updated Apr 23, 2026 · 137 views · 1 min read

Set Up the Application

cd /var/www
mkdir myflask && cd myflask
python3 -m venv venv
source venv/bin/activate
pip install flask gunicorn

Create app.py:

from flask import Flask
app = Flask(__name__)

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

@app.route("/health")
def health():
    return "OK"

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

Test with Gunicorn

gunicorn --bind 0.0.0.0:8000 app:app

Create Systemd Service

Create /etc/systemd/system/flask.service:

[Unit]
Description=Gunicorn Flask App
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/myflask
ExecStart=/var/www/myflask/venv/bin/gunicorn --workers 3 --bind unix:flask.sock app:app
Restart=on-failure

[Install]
WantedBy=multi-user.target
sudo systemctl enable --now flask

Nginx Configuration

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://unix:/var/www/myflask/flask.sock;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /static {
        alias /var/www/myflask/static;
        expires 30d;
    }
}

SSL

sudo certbot --nginx -d example.com

Gunicorn Workers

Formula: (2 * CPU_CORES) + 1

  • 1 CPU: 3 workers
  • 2 CPU: 5 workers
  • 4 CPU: 9 workers

Was this article helpful?