Python’s built-in development servers (manage.py runserver, flask run) are not meant for production. A proper deployment uses an application server — Gunicorn for WSGI apps such as Django and Flask, or Gunicorn with Uvicorn workers for async apps such as FastAPI — managed by systemd, with Nginx in front for HTTPS, static files and buffering. This guide sets that up on Ubuntu or Debian.
Architecture
Visitor ─HTTPS─▶ Nginx :443 ─▶ unix socket ─▶ Gunicorn (N workers) ─▶ your app
└── /static/ and /media/ served directly
Step 1: System packages
sudo apt update
sudo apt install python3 python3-venv python3-dev build-essential nginx -y
python3 --version
Ubuntu 24.04 ships Python 3.12; Debian 12 ships 3.11. If your app needs a different version, install it with your distribution’s tools or a tool such as uv or pyenv, and use that interpreter to create the virtual environment.
Database client libraries, if needed: libpq-dev (PostgreSQL) or default-libmysqlclient-dev pkg-config (MySQL/MariaDB).
Step 2: App user and code
sudo adduser --system --group --home /srv/myapp myapp
sudo -u myapp git clone https://github.com/you/myapp.git /srv/myapp/app
Step 3: Virtual environment
sudo -u myapp python3 -m venv /srv/myapp/venv
sudo -u myapp /srv/myapp/venv/bin/pip install --upgrade pip
sudo -u myapp /srv/myapp/venv/bin/pip install -r /srv/myapp/app/requirements.txt
sudo -u myapp /srv/myapp/venv/bin/pip install gunicorn
# FastAPI / async apps also need:
sudo -u myapp /srv/myapp/venv/bin/pip install "uvicorn[standard]"
Always use a virtual environment. Installing packages system-wide with pip conflicts with the operating system’s own Python packages (recent Debian and Ubuntu refuse it by default).
Step 4: Configuration and secrets
Keep secrets out of the code, in an environment file readable only by the app:
sudo -u myapp nano /srv/myapp/.env
sudo chmod 600 /srv/myapp/.env
DJANGO_SETTINGS_MODULE=myapp.settings.production
SECRET_KEY=generate-a-long-random-value
DATABASE_URL=postgres://myapp:password@localhost/myapp
ALLOWED_HOSTS=example.com,www.example.com
Django-specific steps
In production settings: DEBUG = False, ALLOWED_HOSTS set, STATIC_ROOT = "/srv/myapp/static", and if behind HTTPS:
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
CSRF_TRUSTED_ORIGINS = ["https://example.com"]
Then:
cd /srv/myapp/app
sudo -u myapp bash -c 'set -a; . /srv/myapp/.env; set +a; /srv/myapp/venv/bin/python manage.py migrate'
sudo -u myapp bash -c 'set -a; . /srv/myapp/.env; set +a; /srv/myapp/venv/bin/python manage.py collectstatic --noinput'
Step 5: Test Gunicorn by hand
cd /srv/myapp/app
sudo -u myapp /srv/myapp/venv/bin/gunicorn --bind 127.0.0.1:8000 myapp.wsgi:application # Django
sudo -u myapp /srv/myapp/venv/bin/gunicorn --bind 127.0.0.1:8000 app:app # Flask (module:object)
sudo -u myapp /srv/myapp/venv/bin/gunicorn -k uvicorn.workers.UvicornWorker --bind 127.0.0.1:8000 main:app # FastAPI
curl http://127.0.0.1:8000 from another terminal should return your page. Stop it with Ctrl+C.
Step 6: systemd service
Create /etc/systemd/system/myapp.service:
[Unit]
Description=myapp Gunicorn
After=network.target
[Service]
User=myapp
Group=www-data
WorkingDirectory=/srv/myapp/app
EnvironmentFile=/srv/myapp/.env
RuntimeDirectory=myapp
ExecStart=/srv/myapp/venv/bin/gunicorn \
--workers 3 \
--bind unix:/run/myapp/gunicorn.sock \
--umask 007 \
--access-logfile - \
--timeout 60 \
myapp.wsgi:application
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure
[Install]
WantedBy=multi-user.target
- A unix socket is slightly faster than TCP and is not reachable from the network.
RuntimeDirectorycreates/run/myappon start, and--umask 007lets thewww-datagroup (Nginx) use the socket. - For FastAPI, add
-k uvicorn.workers.UvicornWorkerand usemain:app.
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
sudo systemctl status myapp
More on unit files: systemd services.
How many workers?
A common starting point for sync workers is 2 × CPU cores + 1. Each worker is a full Python process, so check memory: ps -o rss,cmd -u myapp. For I/O-heavy apps, --threads 4 (gthread worker) or async workers can serve more requests with the same memory.
Step 7: Nginx
/etc/nginx/sites-available/example.com:
server {
listen 80;
server_name example.com www.example.com;
client_max_body_size 20M;
location /static/ {
alias /srv/myapp/static/;
expires 30d;
access_log off;
}
location /media/ {
alias /srv/myapp/media/;
}
location / {
proxy_pass http://unix:/run/myapp/gunicorn.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;
proxy_read_timeout 60s;
}
}
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
Nginx needs permission to traverse /srv/myapp to read static files: sudo chmod 750 /srv/myapp && sudo chgrp www-data /srv/myapp (and the static directory must be group-readable).
Step 8: HTTPS
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com --redirect
Deploying updates
cd /srv/myapp/app
sudo -u myapp git pull
sudo -u myapp /srv/myapp/venv/bin/pip install -r requirements.txt
# Django: migrate and collectstatic as above
sudo systemctl reload myapp # graceful: new workers start, old ones finish their requests
Background tasks
Long jobs (sending emails, generating reports, calling slow APIs) should not run inside web requests. Use a task queue such as Celery or RQ with Redis, running as a second systemd service. Scheduled jobs can be cron or systemd timers.
Troubleshooting
| Problem | Check |
|---|---|
| 502 Bad Gateway | systemctl status myapp; journalctl -u myapp -n 50; socket path matches |
| Permission denied on socket | Group=www-data and --umask 007 in the unit |
| Static files 404 | collectstatic run? alias path ends with /? Nginx can traverse directories? |
| Django “DisallowedHost” | ALLOWED_HOSTS |
| CSRF failures after HTTPS | CSRF_TRUSTED_ORIGINS, SECURE_PROXY_SSL_HEADER |
| Workers killed with “WORKER TIMEOUT” | Slow requests — raise --timeout or move work to a background queue |