On this page
- Why do you need Gunicorn and Nginx for Flask?
- What should be ready before you begin?
- How do you set up the application folder and virtual environment?
- How do you test Gunicorn by hand?
- How do you run Gunicorn as a systemd service?
- How do you configure Nginx as the reverse proxy?
- How do you open the firewall and add HTTPS?
- How do you ship updates without downtime?
- Can you use uWSGI instead of Gunicorn?
- How do you troubleshoot a 502 Bad Gateway?
- Questions
Why do you need Gunicorn and Nginx for Flask?
Gunicorn runs several Python worker processes that handle requests in parallel and restarts any that crash, while Nginx handles everything a Python process is bad at: TLS, slow clients, compression, buffering and static files. Flask itself is only the application. Its development server is single purpose, prints a warning on start, and lacks the robustness a public site needs.
The resulting chain is simple: browser to Nginx on 443, Nginx to Gunicorn on localhost, Gunicorn to your Flask code. Only Nginx is reachable from outside.
What should be ready before you begin?
You need a server with a sudo user, a domain whose A and AAAA records point at the server (for example app.example.net to 198.51.100.24 and 2001:db8:4f2a::24, see DNS records), and Python 3 with venv. Install the packages for your system:
# Ubuntu and Debian
sudo apt update
sudo apt install -y python3-venv python3-dev build-essential nginx
# Rocky Linux and AlmaLinux 9
sudo dnf install -y python3.12 python3.12-devel gcc nginx
sudo systemctl enable --now nginx
nginx -v
python3 --versionOn Rocky and Alma use python3.12 in the following commands wherever python3 appears, since the default 3.9 is old for current Flask releases. Background on interpreters is in installing Python 3, pip and venv.
How do you set up the application folder and virtual environment?
Create a folder owned by the user that will run the service, then build a virtual environment inside it.
sudo mkdir -p /srv/flaskapp
sudo chown deploy:deploy /srv/flaskapp
cd /srv/flaskapp
python3 -m venv .venv
.venv/bin/pip install --upgrade pip
.venv/bin/pip install flask gunicorn
.venv/bin/flask --versionNow add a minimal application and a separate WSGI entry file. ProxyFix makes Flask trust the forwarded headers from Nginx, so generated URLs use https and logs show the real client address.
cat > app.py <<'EOF'
from flask import Flask, jsonify
from werkzeug.middleware.proxy_fix import ProxyFix
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
@app.get("/")
def index():
return "Flask is running behind Gunicorn"
@app.get("/health")
def health():
return jsonify(status="ok")
EOF
cat > wsgi.py <<'EOF'
from app import app
EOF
.venv/bin/pip freeze > requirements.txtHow do you test Gunicorn by hand?
Start Gunicorn in the foreground, call it with curl from a second SSH session, then stop it with Ctrl+C.
cd /srv/flaskapp
.venv/bin/gunicorn --workers 2 --bind 127.0.0.1:8000 wsgi:app
# second terminal
curl -s http://127.0.0.1:8000/healthThe reply should be {"status":"ok"}. The argument wsgi:app means "module wsgi, object app". If Gunicorn reports it cannot find the app, check that you are in the right folder and that the names match. Next, move the settings into a config file so the service unit stays short:
cat > gunicorn.conf.py <<'EOF'
import multiprocessing
bind = "127.0.0.1:8000"
workers = multiprocessing.cpu_count() * 2 + 1
timeout = 30
accesslog = "-"
errorlog = "-"
EOFThe 2 x vCPU + 1 rule is a starting point for typical request and database work; lower it on a 1 GB plan, because every worker holds its own copy of the app in memory.
How do you run Gunicorn as a systemd service?
A unit file starts Gunicorn at boot, restarts it on failure and gives you graceful reloads.
sudo tee /etc/systemd/system/flaskapp.service >/dev/null <<'EOF'
[Unit]
Description=Flask app served by Gunicorn
After=network.target
[Service]
User=deploy
Group=deploy
WorkingDirectory=/srv/flaskapp
Environment="PATH=/srv/flaskapp/.venv/bin"
ExecStart=/srv/flaskapp/.venv/bin/gunicorn -c gunicorn.conf.py wsgi:app
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now flaskapp
systemctl status flaskapp --no-pager
ss -ltnp | grep 8000Read the application log with journalctl -u flaskapp -f. Secrets such as a database password belong in an EnvironmentFile= readable only by root and the service, not in the unit itself.
How do you configure Nginx as the reverse proxy?
Create a server block that forwards to Gunicorn and serves /static straight from disk. On Ubuntu and Debian it goes in sites-available; on Rocky and Alma, in /etc/nginx/conf.d/.
server {
listen 80;
listen [::]:80;
server_name app.example.net;
client_max_body_size 10m;
location /static/ {
alias /srv/flaskapp/static/;
expires 7d;
}
location / {
proxy_pass http://127.0.0.1:8000;
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;
proxy_read_timeout 60s;
}
}# Ubuntu and Debian
sudo nano /etc/nginx/sites-available/flaskapp
sudo ln -s /etc/nginx/sites-available/flaskapp /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
# Rocky and Alma: save as /etc/nginx/conf.d/flaskapp.conf, then allow proxying under SELinux
sudo setsebool -P httpd_can_network_connect 1
sudo semanage fcontext -a -t httpd_sys_content_t "/srv/flaskapp/static(/.*)?"
sudo restorecon -Rv /srv/flaskapp
sudo nginx -t && sudo systemctl reload nginx
curl -s -H "Host: app.example.net" http://127.0.0.1/healthMore proxy options are explained in the Nginx reverse proxy guide.
How do you open the firewall and add HTTPS?
Allow web traffic, keep SSH open, then let certbot fetch a free certificate and rewrite the server block for port 443.
# Ubuntu and Debian
sudo ufw allow OpenSSH
sudo ufw allow "Nginx Full"
sudo ufw enable
sudo apt install -y certbot python3-certbot-nginx
# Rocky and Alma
sudo firewall-cmd --permanent --add-service=http --add-service=https
sudo firewall-cmd --reload
sudo dnf install -y epel-release && sudo dnf install -y certbot python3-certbot-nginx
sudo certbot --nginx -d app.example.net
sudo certbot renew --dry-run
curl -sI https://app.example.net/healthPort 8000 stays closed: Gunicorn listens only on localhost, so the firewall does not need a rule for it. Certificate details and renewals are covered in Certbot and Let's Encrypt.
How do you ship updates without downtime?
Pull the new code, update dependencies, then send Gunicorn a reload: it starts fresh workers with the new code and retires the old ones after they finish their requests.
cd /srv/flaskapp
git pull
.venv/bin/pip install -r requirements.txt
sudo systemctl reload flaskapp
journalctl -u flaskapp -n 20 --no-pagerUse restart instead of reload after changing gunicorn.conf.py or the Python version. For automatic deploys on push, see Git deploy hooks.
Can you use uWSGI instead of Gunicorn?
Yes. uWSGI is an older, very configurable application server that Nginx can talk to over its own binary protocol. The project is in maintenance mode (bug fixes, no new features), so Gunicorn is the simpler pick for new deployments, but existing uWSGI setups keep working. The pyuwsgi package ships prebuilt wheels and avoids compiling.
/srv/flaskapp/.venv/bin/pip install pyuwsgi
cat > /srv/flaskapp/uwsgi.ini <<'EOF'
[uwsgi]
module = wsgi:app
master = true
processes = 3
socket = 127.0.0.1:8001
vacuum = true
die-on-term = true
EOF
/srv/flaskapp/.venv/bin/uwsgi --ini /srv/flaskapp/uwsgi.iniIn Nginx, replace the proxy_pass block with include uwsgi_params; and uwsgi_pass 127.0.0.1:8001;, and point the systemd ExecStart at the uwsgi command.
How do you troubleshoot a 502 Bad Gateway?
A 502 means Nginx could not reach Gunicorn. Work through these checks in order:
systemctl status flaskapp: is the service running, or did it crash on an import error?journalctl -u flaskapp -n 50: Python tracebacks appear here.ss -ltnp | grep 8000: is anything listening on the port Nginx uses?sudo tail /var/log/nginx/error.log: "connection refused" points at Gunicorn, "permission denied" on Rocky or Alma points at SELinux.sudo ausearch -m avc -ts recent: shows SELinux denials if the boolean was not set.
A 504 instead means Gunicorn answered too slowly; raise timeout or move long jobs to a task queue such as Celery with Redis.
Plans that fit this guide
Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.
Questions about Deploy Flask with Gunicorn and Nginx
Should Gunicorn use a Unix socket or a TCP port?
Both work. A localhost TCP port is easier to test with curl and needs no shared group between Nginx and the app user; a Unix socket saves a little overhead. This guide uses TCP to keep SELinux setup simple on Rocky and Alma.
How many Gunicorn workers should I run?
Start with two per vCPU plus one and watch memory with free -h. On a 1 GB plan, two or three workers is often the comfortable limit.
Where do I set FLASK_ENV or debug mode?
Never enable debug mode in production, because the debugger allows code execution. Keep configuration in environment variables loaded through EnvironmentFile= in the unit.
Can I host several Flask apps on one server?
Yes. Give each its own folder, service and port (8000, 8001 and so on) and its own Nginx server block with a different server_name.
Does the same setup work for Django?
The pattern is identical with a different WSGI module. See Deploy Django with Gunicorn and Nginx for the Django specific steps.
More in Python
- Install Python 3, pip and venv
- Run legacy Python 2 code
- Manage Python projects with Poetry
- Miniconda and Anaconda on a server
- Deploy FastAPI with Uvicorn workers
- Deploy Django with Gunicorn and Nginx
- Background tasks with Celery and Redis
- Host a Python Discord bot
- Containerise a Python web app
- JupyterLab on a server
- Host a Python Telegram bot