How to Deploy a Python App with Gunicorn and Nginx
How to deploy a Python app (Flask or Django) on Linux: venv, Gunicorn, systemd, Nginx reverse proxy, static files, HTTPS, updates and common errors.

Contents
- Requirements
- Step 1: Python, venv and Nginx
- Step 2: User, code and virtual environment
- Step 3: Test Gunicorn
- Step 4: Environment variables
- Step 5: Django production settings
- Step 6: systemd service for Gunicorn
- Step 7: Nginx reverse proxy
- Step 8: HTTPS
- Deploying updates
- Logs and common errors
- A note on FastAPI
- Nodesty servers for Python apps
To deploy a Python app like Flask or Django to production, you need more than the development server: a virtual environment for the dependencies, Gunicorn as the application server, systemd to keep it running and Nginx in front for HTTPS and static files. Once this setup is in place, every update comes down to a handful of commands.
This guide walks through deploying a Flask or Django application on a clean Ubuntu server: preparing the server, testing Gunicorn, writing the systemd service, configuring Nginx, Django production settings, HTTPS, updates and the most common errors.
Requirements
- Server: An Ubuntu server with root access. In this guide we use Ubuntu 24.04.
- Application: A Flask or Django project in a Git repository with a
requirements.txtfile. - Database: If your app uses one, see our How to install PostgreSQL guide.
- Domain: An A record pointing to your server's IP address.
Step 1: Python, venv and Nginx
After connecting to your server with SSH:
sudo apt update
sudo apt install python3 python3-venv python3-pip nginx git
On AlmaLinux, the equivalent is sudo dnf install python3 python3-pip nginx git; the venv module comes with python3 there. Nginx runs as the nginx user instead of www-data and site files go in /etc/nginx/conf.d/. See our How to install Nginx guide for the basics.
Step 2: User, code and virtual environment
Don't run the application as root. Create a user for it, a folder under /srv and a virtual environment inside it:
sudo adduser --disabled-password --gecos "" deploy
sudo mkdir -p /srv/app
sudo chown deploy:deploy /srv/app
sudo -iu deploy
git clone git@github.com:user/app.git /srv/app
cd /srv/app
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt gunicorn
The virtual environment keeps your packages separate from the system Python; Ubuntu 24.04 blocks pip install outside a venv anyway (the "externally-managed-environment" error). If you use PostgreSQL with Django, make sure psycopg is in requirements.txt. We cover deploy keys in our How to deploy with Git guide and managing users in How to add a user on Linux. Run the commands in the next steps as the deploy user unless they start with sudo.
Step 3: Test Gunicorn
Before writing any service file, check that Gunicorn can load the app. The argument is module:variable:
# Flask: app.py contains app = Flask(__name__)
gunicorn --bind 127.0.0.1:8000 app:app
# Django: the project folder that contains wsgi.py
gunicorn --bind 127.0.0.1:8000 project.wsgi:application
From a second SSH session, curl -I http://127.0.0.1:8000 should return a response. If your Flask app uses an application factory, use "app:create_app()". Stop Gunicorn with Ctrl+C.
Two settings matter in production:
- Workers: A rule of thumb is
2 × CPU cores + 1; check the core count withnproc. Each worker is a separate process, so more workers also means more RAM. - Timeout: Gunicorn restarts a worker that doesn't answer within 30 seconds by default. Raise it with
--timeout 60only if you really have slow requests; long jobs belong in a background queue.
Step 4: Environment variables
Keep secrets out of the code and the repository. Generate a secret key with python3 -c "import secrets; print(secrets.token_urlsafe(50))", which avoids characters that cause trouble in the file, and create /etc/app.env from your admin account:
DJANGO_SECRET_KEY=paste-the-generated-value-here
DB_PASSWORD=a-strong-password
Write one KEY=value per line, without export and without spaces around =. Then protect the file with sudo chown root:deploy /etc/app.env and sudo chmod 640 /etc/app.env, and read the values in your code with os.environ.
Step 5: Django production settings
Skip this step for Flask. In settings.py, change at least these values:
import os
DEBUG = False
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
ALLOWED_HOSTS = ["example.com", "www.example.com"]
CSRF_TRUSTED_ORIGINS = ["https://example.com", "https://www.example.com"]
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
DEBUG = False: With debug on, error pages show your settings and code to visitors.ALLOWED_HOSTS: Requests for any other host name get a 400 error (DisallowedHost).CSRF_TRUSTED_ORIGINSandSECURE_PROXY_SSL_HEADER: Behind Nginx, Django sees plain HTTP. These let it trust theX-Forwarded-Protoheader so forms work over HTTPS. Only use the header setting when Nginx sets it, as below.
Then load the variables into your shell and prepare the database and static files:
set -a; . /etc/app.env; set +a
python manage.py migrate
python manage.py collectstatic --noinput
Step 6: systemd service for Gunicorn
Leave the deploy shell with exit and create /etc/systemd/system/app.service:
[Unit]
Description=Gunicorn for app
After=network.target
[Service]
User=deploy
Group=www-data
WorkingDirectory=/srv/app
EnvironmentFile=/etc/app.env
RuntimeDirectory=app
ExecStart=/srv/app/venv/bin/gunicorn --workers 3 --timeout 60 \
--access-logfile - --bind unix:/run/app/gunicorn.sock project.wsgi:application
Restart=always
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now app
ExecStart uses the full path to the venv's gunicorn, so there's no need to activate anything. RuntimeDirectory creates /run/app at every start. For Flask, replace the last argument with app:app. If you prefer TCP, use --bind 127.0.0.1:8000 here and proxy_pass http://127.0.0.1:8000; in Nginx. We explain unit files in our How to create a systemd service guide.
Step 7: Nginx reverse proxy
Create /etc/nginx/sites-available/app:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
client_max_body_size 20M;
location /static/ {
alias /srv/app/staticfiles/;
}
location / {
proxy_pass http://unix:/run/app/gunicorn.sock;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
sudo ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
aliasserves static files straight from disk, without going through Python. Keep the trailing slashes on both sides.client_max_body_size: Nginx allows 1 MB uploads by default; larger files get a 413 error.- For Flask, wrap the app with Werkzeug's
ProxyFixso it trusts these headers when building URLs.
Open only the web ports in the firewall with sudo ufw allow 'Nginx Full'; port 8000 stays closed. See our How to use UFW guide.
Step 8: HTTPS
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
Certbot gets the certificate, adds the HTTPS server block and sets up automatic renewal. See our What is an SSL certificate? article for details.
Deploying updates
sudo -iu deploy
cd /srv/app
git pull
source venv/bin/activate
pip install -r requirements.txt
set -a; . /etc/app.env; set +a
python manage.py migrate
python manage.py collectstatic --noinput
exit
sudo systemctl restart app
Gunicorn keeps the old code in memory until it restarts. Back up the database before migrations that change data; see our server backups guide.
Logs and common errors
Gunicorn's output goes to the journal (sudo journalctl -u app -f), and Nginx writes to /var/log/nginx/error.log.
| Error | Common cause |
|---|---|
| 502 Bad Gateway | Gunicorn isn't running, or Nginx can't open the socket (for example a socket in /home/deploy) |
| Static files return 404 | collectstatic wasn't run or the alias path doesn't match STATIC_ROOT |
| 400 Bad Request, DisallowedHost | The domain is missing from ALLOWED_HOSTS |
| 403 CSRF verification failed | CSRF_TRUSTED_ORIGINS is missing the https:// origin |
| ModuleNotFoundError | The package isn't in the venv, or the service runs a gunicorn outside /srv/app/venv |
If the service fails to start, journalctl usually shows the Python traceback; a KeyError: 'DJANGO_SECRET_KEY' means the EnvironmentFile wasn't loaded. For a step-by-step 502 checklist, see our 502 Bad Gateway guide.
A note on FastAPI
FastAPI and other ASGI apps need an ASGI worker. Install uvicorn in the venv and change the Gunicorn command to gunicorn -k uvicorn.workers.UvicornWorker main:app; recent Uvicorn versions move this worker to the separate uvicorn-worker package (-k uvicorn_worker.UvicornWorker). You can also run uvicorn main:app --workers 4 --uds /run/app/gunicorn.sock directly. Nginx and systemd stay the same.
Nodesty servers for Python apps
Nodesty AMD Ryzen 9 9950X VPS plans give Python requests low response times with high single-core speed, while AMD EPYC 7763 VPS plans offer plenty of cores and RAM for more Gunicorn workers, the database and background jobs on the same server. With full root access, NVMe storage, nShield DDoS protection and free daily backups kept for 7 days, you can deploy your Flask, Django or FastAPI projects with confidence.
Frequently Asked Questions
Why not just run python app.py or manage.py runserver on the server?
Flask's built-in server and Django's runserver are development servers. They are not designed for security or performance under real traffic. Gunicorn runs several worker processes, restarts crashed workers and works well behind Nginx, which handles HTTPS, static files and slow clients.
How many Gunicorn workers should I use?
A common starting point is two workers per CPU core plus one, so 5 workers on a 2-core server. Each worker is a separate process with its own memory, so watch RAM usage and lower the number if the server starts swapping. Measure under real load and adjust from there.
Should Gunicorn listen on a Unix socket or on 127.0.0.1:8000?
Both work. A Unix socket avoids the TCP stack and can't be reached from the network at all, while 127.0.0.1:8000 is easier to test with curl and avoids socket permission problems. Never bind Gunicorn to 0.0.0.0 in production; let only Nginx face the internet.
Why does my site show a 502 Bad Gateway error?
Nginx couldn't reach Gunicorn. Either the Gunicorn service isn't running, it crashed while starting, or Nginx isn't allowed to open the socket. Check systemctl status and journalctl for the Gunicorn service, then the Nginx error log in /var/log/nginx/error.log.
Can I deploy a FastAPI app the same way?
Yes. FastAPI is an ASGI framework, so run it with Uvicorn workers under Gunicorn or with Uvicorn directly. The rest of the setup, the virtual environment, the systemd service, the Nginx reverse proxy and HTTPS, stays the same.
About the author
Nodesty Team · Infrastructure & Support
The Nodesty team runs our servers, network and DDoS protection day to day and answers customer support requests around the clock. These guides come from that work.
Related articles

How to Install a LEMP Stack on Ubuntu and Debian
How to install a LEMP stack on Ubuntu and Debian: Nginx, MariaDB and PHP-FPM, the server block, the PHP socket, permissions, HTTPS and common errors.

How to Use tmux: Keep Programs Running After SSH Closes
Learn how to use tmux on a Linux server: keep programs running after SSH closes, detach and reattach sessions, split panes, scroll and fix common errors.

How to Deploy a Node.js App with PM2 and Nginx
How to deploy a Node.js app on a Linux VPS: Node.js LTS, npm ci, PM2 with autostart and reload, an Nginx reverse proxy, HTTPS, updates and common errors.