VPS Tutorials
Deploy Django and FastAPI on a VPS: Python, Gunicorn and Nginx
Deploy Python applications on Ubuntu 24.04 with virtual environments, suitable WSGI/ASGI workers, systemd, Nginx static files and HTTPS. Configure Django, migrations, release recovery and Celery, with limits on graceful reload explained.

A project that works with runserver or uvicorn main:app --reload locally may fail on a VPS: pip install encounters externally-managed-environment, static assets return 404, DEBUG=False reveals production configuration errors, or the process disappears after closing SSH. This Ubuntu 24.04 guide covers Python, virtual environments, WSGI/ASGI workers, systemd, Unix sockets, Nginx, Django settings and releases. Flask and Litestar need the corresponding application entrypoint and server mode.
| Responsibility | Component | Purpose |
|---|---|---|
| Execute application code | Gunicorn/Uvicorn | runserver is a development server; Django's default server can be threaded, but is unsuitable for production |
| Supervision and boot startup | systemd | Keeps the service independent of the terminal and restarts failures |
| Public ports, TLS and assets | Nginx/Caddy | Avoids a root application process and can serve files directly |
| Certificate renewal | Certbot/Caddy | Prevents expiration when correctly configured and monitored |
Request flow:
浏览器 → Nginx(443) → Unix socket → Gunicorn → 你的 Django/FastAPI 代码
↓
/static/ 直接由 Nginx 返回,不进 Python
Both Node and Python can handle concurrent I/O; Python ASGI does not require a process per concurrent request. Gunicorn workers are independent processes. The source's 80–150 MB per ordinary Django worker and 300 MB or more with heavy libraries are illustrative, not measurements of your application. The familiar (2 × CPU核数) + 1 formula is only a starting heuristic.
| VPS example | Worker range to evaluate | Qualification |
|---|---|---|
| 2 vCPU / 2 GB | 2–3 | Start at 2; the formula's 5 may exceed memory |
| 2 vCPU / 4 GB | 3–5 | Measure request cost and connection pools |
| 4 vCPU / 8 GB | 5–9 | The source reserves 2 GB for DB/system; actual needs may be larger |
Inspect RSS with ps aux | grep gunicorn, estimate total worker memory and leave at least the source's 30% example headroom for database, cache and OS; validate this margin under load.
- pandas, NumPy and Pillow can substantially increase resident memory.
- An I/O-heavy ASGI API may start with 2–4 workers; that is not a high-concurrency guarantee.
- SSD I/O matters for virtual environments containing many small files.
RackNerd annual plans, Vultr hourly resizing and Contabo memory offers are selection examples: verify current pricing and measure disk performance. BandwagonHost CN2 GIA addresses mainland-China connectivity, not worldwide latency. Use the VPS sizing guide.
Ubuntu 24.04 supplies Python 3.12. Check the actual locked framework and library requirements before replacing it. The September source cited Django 6.1 requiring 3.12+, FastAPI 0.141 requiring 3.10+, and Gunicorn 26/Uvicorn 0.53 requiring 3.10+; these are historical package references.
At the 16 November 2026 registry check, Django 6.1.3 requires 3.12+, FastAPI 0.163.1 requires 3.11+, Gunicorn 27.0.1 and Uvicorn 0.54.0 require 3.10+. Ubuntu's 3.12 satisfies these lower bounds, subject to your full dependency set. The source's Python 3.14 release in October 2025 and support through October 2030 are lifecycle references, not a claim that 3.14 is still the newest release. Python 3.12's upstream security lifecycle runs through October 2028; the source's October 2026 retirement date for 3.10 has passed. Plan migration off it. Check the official Python lifecycle and distribution support separately.
Prefer distribution-maintained 3.12 when adequate. Free-threading is not enabled merely by installing a newer ordinary interpreter; it requires the appropriate build and compatible extensions.
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3 python3-venv python3-dev build-essential \
libpq-dev nginx git curl ufw
python3 -V
python3-dev and build-essential help compile psycopg, pillow and lxml when no compatible wheel exists; missing headers commonly cause gcc errors. libpq-dev is for PostgreSQL; MySQL may require default-libmysqlclient-dev.
Only if a newer interpreter is required, evaluate the third-party deadsnakes PPA and its support policy:
sudo add-apt-repository -y ppa:deadsnakes/ppa
sudo apt install -y python3.14 python3.14-venv python3.14-dev
System-wide pip install django may produce:
error: externally-managed-environment
× This environment is externally managed
Ubuntu marks its interpreter as externally managed to avoid overwriting apt dependencies. Use a virtual environment instead of bypassing protection with --break-system-packages:
sudo useradd -r -m -d /srv/app -s /bin/bash appuser
sudo mkdir -p /srv/app/{releases,shared}
sudo chown -R appuser:appuser /srv/app
sudo -u appuser python3 -m venv /srv/app/shared/venv
sudo -u appuser /srv/app/shared/venv/bin/pip install --upgrade pip
The source places the environment under shared/ for reuse. For reliable rollback, prefer a separate environment per release: modifying a shared environment can break the still-running release and changes its dependencies before switching code.
An optional uv workflow is:
curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv /srv/app/shared/venv --python 3.12
uv pip install --python /srv/app/shared/venv/bin/python -r requirements.txt
Review the installer, run it as the intended deployment account and ensure directory permissions. Registry uv 0.13.8 supersedes the source's 0.12 series; speed depends on caching, wheels and network. It accepts requirements.txt without requiring a project restructure.
Provision repository SSH access for appuser, verify the host key and replace the repository/date placeholders:
sudo -u appuser git clone [email protected]:your/repo.git /srv/app/releases/20260920-140000
cd /srv/app/releases/20260920-140000
sudo -u appuser /srv/app/shared/venv/bin/pip install -r requirements.txt
sudo -u appuser /srv/app/shared/venv/bin/pip install gunicorn
Lock requirements.txt using exact references such as django==6.1.1 rather than open constraints such as django>=6.1. Those strings are examples, not recommendations to retain an unpatched version. pip freeze > requirements.txt records an installed environment; uv pip compile can produce a compiled lock with hashes. Include the selected application server and worker package in the lock rather than installing an unpinned Gunicorn on each release.
/srv/app/shared/venv/bin/gunicorn \
--workers 3 \
--bind unix:/srv/app/shared/gunicorn.sock \
--timeout 60 \
--access-logfile - \
--error-logfile - \
myproject.wsgi:application
In myproject.wsgi:application, replace myproject with the package containing settings.py. A Unix socket avoids public TCP exposure but requires the proxy and server on the same machine and correct permissions. Private loopback TCP is also a valid choice.
An async def application needs an ASGI-capable worker. The source's legacy Uvicorn example is:
/srv/app/shared/venv/bin/gunicorn \
--workers 3 \
--worker-class uvicorn.workers.UvicornWorker \
--bind unix:/srv/app/shared/gunicorn.sock \
--timeout 60 \
main:app
The uvicorn.workers module is deprecated. Install a tested, locked uvicorn-worker package and replace the worker class with uvicorn_worker.UvicornWorker; update the systemd entrypoint to main:app for FastAPI. See the maintained worker. Direct uvicorn --workers 3 under systemd is another supported multiprocess option.
--timeout generally concerns a worker's lack of communication with Gunicorn, not a universal per-request deadline; behavior differs by worker class. The default is 30 seconds. Put long exports or model calls in a queue such as Celery and define application/proxy deadlines deliberately.
Save /etc/systemd/system/myapp.service:
[Unit]
Description=Django/FastAPI App via Gunicorn
After=network.target postgresql.service
[Service]
Type=notify
User=appuser
Group=www-data
WorkingDirectory=/srv/app/current
EnvironmentFile=/srv/app/shared/.env
ExecStart=/srv/app/shared/venv/bin/gunicorn \
--workers 3 \
--bind unix:/srv/app/shared/gunicorn.sock \
--umask 007 \
--timeout 60 \
--access-logfile - \
--error-logfile - \
myproject.wsgi:application
ExecReload=/bin/kill -s HUP $MAINPID
Restart=always
RestartSec=3
KillMode=mixed
TimeoutStopSec=30
MemoryMax=1500M
LimitNOFILE=65535
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/srv/app/shared
[Install]
WantedBy=multi-user.target
Prepare current to point to an existing release, plus shared static/media directories, before enabling the service. Match the chosen WSGI or ASGI entrypoint. The 1500M hard limit requires a VPS with sufficient room for other services.
Group=www-dataand--umask 007grant socket access towww-data; parent directories also need traversal permissions. Otherwise Nginx reportsconnect() to unix:/... failed (13: Permission denied).Type=notifyuses Gunicorn's readiness notification; unlikeType=simple, it can wait for server initialization. Verify behavior with your locked version and worker.ExecReload=kill -s HUPsends HUP for graceful worker replacement, but does not guarantee that a changed release symlink changes the master's working directory or that systemd reloads environment values.- With
ProtectSystem=strict, declare writable directories inReadWritePathsto avoidRead-only file system. Keep secrets read-only to the application where practical. After=postgresql.serviceprovides ordering, not database readiness. Implement connection retries and use the actual database service name.
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
sudo systemctl status myapp
On failure inspect journalctl -u myapp -n 50 --no-pager and the systemd checklist.
Save the configuration in /etc/nginx/sites-available/app.example.com before creating its enabled link:
upstream app_server {
server unix:/srv/app/shared/gunicorn.sock fail_timeout=0;
}
server {
listen 80;
listen [::]:80;
server_name app.example.com;
client_max_body_size 20m;
access_log /var/log/nginx/app.access.log;
error_log /var/log/nginx/app.error.log warn;
# 静态文件直接由 Nginx 返回,不进 Python
location /static/ {
alias /srv/app/shared/static/;
expires 30d;
access_log off;
add_header Cache-Control "public, immutable";
}
location /media/ {
alias /srv/app/shared/media/;
expires 7d;
}
location / {
proxy_pass http://app_server;
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_redirect off;
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
}
}
sudo ln -s /etc/nginx/sites-available/app.example.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
X-Forwarded-Proto must be passed and trusted consistently with Django SECURE_SSL_REDIRECT; otherwise TLS termination can cause redirect loops. Trust only your proxy, which must overwrite client-supplied protocol headers. See redirect-loop diagnosis.
Keep trailing slashes on alias directory mappings. Ensure Nginx can traverse and read the files. Immutable caching is appropriate for content-hashed assets, not arbitrary changing filenames. Public /media/ serves uploads without application authorization; private media needs a protected delivery design. Use Nginx hardening or the Caddy guide.
Replace domain/mail placeholders, check A/AAAA records and allow the required cloud/UFW ports before issuance:
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d app.example.com --redirect --agree-tos -m [email protected]
systemctl list-timers | grep certbot
sudo certbot renew --dry-run
Monitor renewal and use the certificate troubleshooting guide.
- Set
DEBUG = False. Debug error pages expose sensitive configuration and diagnostic information. - Set
ALLOWED_HOSTS. WithDEBUG = False, an emptyALLOWED_HOSTSrejects normal requests; list actual hostnames without URL schemes. - Load
SECRET_KEYfrom protected configuration:
import os
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = os.environ.get("DJANGO_DEBUG", "0") == "1"
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",")
STATIC_ROOT = "/srv/app/shared/static"
STATIC_URL = "/static/"
MEDIA_ROOT = "/srv/app/shared/media"
MEDIA_URL = "/media/"
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_TRUSTED_ORIGINS = ["https://app.example.com"]
os.environ["..."] fails immediately when a required secret is absent, unlike a permissive .get(). Set real CSRF origins and secure-cookie settings for the deployment. A DATABASE_URL string also needs an explicit parser or DATABASES configuration; Django does not consume it automatically.
- Run
collectstatic:
sudo -u appuser /srv/app/shared/venv/bin/python manage.py collectstatic --noinput
sudo -u appuser /srv/app/shared/venv/bin/python manage.py migrate
With DEBUG = False, production static delivery needs collectstatic populating STATIC_ROOT and matching Nginx routing. Missing CSS can also be permissions or cache problems. Management commands need the correct working directory and environment; systemd's EnvironmentFile is not automatically loaded in your shell.
sudo -u appuser touch /srv/app/shared/.env
sudo chmod 600 /srv/app/shared/.env
The source template contains an instruction in its secret value; replace it with the output of Python's secrets.token_urlsafe(50), not the instruction itself:
DJANGO_SECRET_KEY=用 python -c "import secrets;print(secrets.token_urlsafe(50))" 生成
DJANGO_DEBUG=0
DJANGO_ALLOWED_HOSTS=app.example.com
DATABASE_URL=postgres://app:[email protected]:5432/appdb
Keep credentials private and explicitly load them for migrations/static collection. Bind a host database to 127.0.0.1 or another private interface. Follow database exposure guidance, PostgreSQL deployment and Redis deployment for cache or Celery broker setup.
The original workflow is retained as a reference:
#!/usr/bin/env bash
set -euo pipefail
APP=/srv/app
VENV=$APP/shared/venv
RELEASE=$APP/releases/$(date +%Y%m%d-%H%M%S)
git clone --depth 1 [email protected]:your/repo.git "$RELEASE"
cd "$RELEASE"
"$VENV/bin/pip" install -r requirements.txt
"$VENV/bin/python" manage.py collectstatic --noinput
"$VENV/bin/python" manage.py migrate --noinput
ln -sfn "$RELEASE" "$APP/current"
sudo systemctl reload myapp
ls -1dt $APP/releases/* | tail -n +6 | xargs -r rm -rf
Run it as the deployment account with narrowly scoped restart privileges, correct secrets and a pre-release database/uploads backup. Do not treat it as verified zero-downtime deployment. systemctl reload signals the existing Gunicorn master; it may keep its old resolved working directory. A shared venv and shared static directory also modify the old release before the switch. Use release-specific dependencies and assets, then a controlled restart that resolves current again, or a tested two-instance/proxy-switch deployment for continuous availability. Verify the running commit and public health after switching.
migrate does not reverse merely because the symlink is restored. Some migrations support reversal, but destructive data changes may not. Expand the schema compatibly first and remove obsolete fields in a later release. Keep set -euo pipefail so a failed migrate stops the switch. Retain the active and rollback releases until health is confirmed; inspect cleanup targets before deletion.
- 502: inspect
sudo systemctl status myapp, worker startup, socketPermission deniedand OOM evidence. See 502/504. - 500 with empty logs: configure Django
LOGGINGto stderr;DEBUG=Falsedisables debug pages, not error logging itself. DisallowedHost/ 400: add the actual hostname toALLOWED_HOSTS.- CSS/JS 404: check
collectstatic,aliasslashes and permissions. WORKER TIMEOUT: investigate slow requests, blocking work and the worker-specific meaning of--timeout; queue long tasks rather than raising it blindly.- Growing memory/OOM:
--max-requests 1000 --max-requests-jitter 100recycles workers and can contain a leak temporarily. Diagnose the cause; swap/ZRAM does not repair it. externally-managed-environment: create a venv, avoiding--break-system-packages.
Use the logging guide and inspect application and proxy logs together:
sudo journalctl -u myapp -f
sudo tail -f /var/log/nginx/app.error.log
Celery does not start with Gunicorn. The source detached-worker unit is:
[Unit]
Description=Celery Worker
After=network.target redis-server.service
[Service]
Type=forking
User=appuser
WorkingDirectory=/srv/app/current
EnvironmentFile=/srv/app/shared/.env
ExecStart=/srv/app/shared/venv/bin/celery -A myproject worker \
--detach --loglevel=info --concurrency=2 \
--pidfile=/srv/app/shared/celery.pid
Restart=always
[Install]
WantedBy=multi-user.target
Prefer a foreground worker under Type=simple: remove --detach and the PID-file option, use the chosen release environment and project, and send logs to the journal. Prepare broker credentials, explicit writable paths and application readiness handling. Enable it as a separate unit and restart it with releases. Celery Beat also needs its own service; run exactly one scheduler per schedule so jobs are not enqueued twice, and make tasks safe to retry.
- Back up the database, uploads, secrets and deployment configuration; Git alone is not recovery. Perform a restore drill.
- For large upload collections, evaluate object storage and its access/backup model; see MinIO.
- Configure bandwidth alerts before reaching provider limits.
- Record initial TTFB and memory for later comparisons; see TTFB diagnosis.
- Node.js deployment for a companion service;
- VPS sizing for worker/memory balance;
- Dokploy for managed Git deployments;
- GitHub Actions runner for CI builds;
- Service unreachable externally for ports, bindings and firewalls.