Django Deployment: Gunicorn, Nginx, and Systemd on a VPS
Deploying a Django application to a VPS with Gunicorn, Nginx, and systemd is the production setup that balances performance, reliability, and operational simplicity. This stack handles thousands of concurrent requests, restarts automatically after crashes, serves static files efficiently, and terminates SSL — all without managed services or vendor lock-in. This guide covers the complete setup from project structure to security hardening, based on our standard deployment configuration for Django projects.
Need help with infrastructure and DevOps? I provide infrastructure and DevOps for businesses ready to grow. Learn about my infrastructure and DevOps service or get in touch for a free consultation.
- Prerequisites
- systemd Service File
- Environment Variable Management
- Security Hardening Checklist
Prerequisites
You need a VPS with Ubuntu 22.04+ (or Debian 12+), a domain pointing to the server's IP, SSH access with key-based authentication (password authentication should already be disabled), and Python 3.12+ installed. For production databases, use PostgreSQL — never SQLite, which does not handle concurrent writes. Install the essentials:
sudo apt update && sudo apt install -y python3-pip python3-venv nginx certbot python3-certbot-nginx postgresql postgresql-contrib
Create a system user for your application rather than running it as root or your personal user. This limits the blast radius if the application is compromised — an attacker who exploits a vulnerability in your Django code gains only the permissions of the application user, not root access.
sudo useradd --system --create-home --shell /bin/bash www-data-app
sudo mkdir -p /srv/projects/myapp
sudo chown www-data-app:www-data-app /srv/projects/myapp
Project Structure on the Server
A clean server-side project structure separates code, virtual environment, static files, media uploads, and logs. This makes deployment, backup, and debugging straightforward.
/srv/projects/myapp/
├── myapp/ # Django project (deployed via git archive or rsync)
│ ├── config/ # settings, urls, wsgi, asgi
│ ├── apps/ # Django apps
│ ├── templates/ # templates
│ ├── manage.py
│ └── requirements.txt
├── venv/ # Python virtual environment
├── staticfiles/ # collectstatic output (served by Nginx)
├── media/ # user uploads (served by Nginx)
├── logs/ # application logs
│ ├── gunicorn-access.log
│ └── gunicorn-error.log
└── .env # environment variables (not in git)
The virtual environment lives outside the project directory so that deployments (which replace the project directory contents) do not destroy installed packages. The .env file contains secrets and is never committed to version control.
For production databases, use PostgreSQL — never SQLite, which does not handle concurrent writes.
Gunicorn Configuration
Gunicorn is a WSGI HTTP server that runs your Django application. The configuration determines how many concurrent requests your application can handle and how it behaves under load.
# /srv/projects/myapp/gunicorn.conf.py
import multiprocessing
bind = "unix:/run/myapp.sock"
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = "gthread"
threads = 4
timeout = 30
graceful_timeout = 30
keepalive = 5
max_requests = 1000
max_requests_jitter = 50
accesslog = "/srv/projects/myapp/logs/gunicorn-access.log"
errorlog = "/srv/projects/myapp/logs/gunicorn-error.log"
loglevel = "info"
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(D)s'
Key configuration choices explained: bind uses a Unix socket instead of a TCP port, which is faster for local communication with Nginx and avoids port conflicts. The workers formula of 2 * CPU + 1 is Gunicorn's recommendation for I/O-bound applications like Django. worker_class = "gthread" with 4 threads per worker handles concurrent requests within each worker process, improving throughput for database-bound views. max_requests = 1000 with jitter restarts workers periodically, preventing memory leaks from accumulating — each worker handles 950-1050 requests (randomized) before being recycled.
For applications with async views or WebSocket support, use worker_class = "uvicorn.workers.UvicornWorker" and point to your ASGI application instead. This handles both HTTP and WebSocket connections. For more on WebSocket deployment, see our guide on real-time dashboards with Django Channels.
For applications with async views or WebSocket support, use worker_class = "uvicorn.workers.UvicornWorker" and point to your ASGI application instead.
systemd Service File
systemd manages the Gunicorn process — starting it on boot, restarting it after crashes, and providing clean shutdown on deploy.
# /etc/systemd/system/myapp.service
[Unit]
Description=MyApp Django Application
After=network.target postgresql.service
Requires=postgresql.service
[Service]
User=www-data-app
Group=www-data-app
WorkingDirectory=/srv/projects/myapp/myapp
Environment="DJANGO_ENV=production"
EnvironmentFile=/srv/projects/myapp/.env
ExecStart=/srv/projects/myapp/venv/bin/gunicorn config.wsgi:application --config /srv/projects/myapp/gunicorn.conf.py
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure
RestartSec=5
KillMode=mixed
TimeoutStopSec=30
# Security hardening
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/srv/projects/myapp/logs /srv/projects/myapp/media
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
The security directives are critical: PrivateTmp gives the process its own /tmp directory, preventing other processes from reading temporary files. ProtectSystem=strict makes the entire filesystem read-only except for explicitly listed ReadWritePaths. NoNewPrivileges prevents the process from gaining additional privileges through setuid binaries. These settings significantly reduce the attack surface.
# Enable and start the service
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp
sudo systemctl status myapp
Nginx Site Configuration
Nginx serves as a reverse proxy, handling SSL termination, static file serving, compression, and connection management. It is significantly more efficient at serving static files and handling slow clients than Gunicorn.
# /etc/nginx/sites-available/myapp
upstream django {
server unix:/run/myapp.sock fail_timeout=0;
}
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://yourdomain.com$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
client_max_body_size 20M;
# Security headers
add_header X-Frame-Options DENY always;
add_header X-Content-Type-Options nosniff always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
# Static files — served directly by Nginx
location /assets/ {
alias /srv/projects/myapp/staticfiles/;
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}
# Media files
location /media/ {
alias /srv/projects/myapp/media/;
expires 30d;
add_header Cache-Control "public";
}
# Django application
location / {
proxy_pass http://django;
proxy_set_header Host $http_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;
}
}
Static files get aggressive caching with immutable — since Django's ManifestStaticFilesStorage hashes filenames, cached files never serve stale content. The access_log off for static files prevents your log files from filling up with requests for CSS, JS, and image files. Enable the site and test:
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
SSL with Certbot
Let's Encrypt provides free SSL certificates. Certbot automates the process including automatic renewal.
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
# Certbot modifies your Nginx config and sets up auto-renewal
# Verify auto-renewal works:
sudo certbot renew --dry-run
Certbot creates a systemd timer that renews certificates automatically before they expire. Verify this is active with systemctl list-timers | grep certbot. If you are behind Cloudflare (which provides its own SSL), you still want a certificate on your origin server for full (strict) SSL mode — Cloudflare connects to your server over HTTPS, verifying the origin certificate.
Want expert help with this? Let's make it happen.
Get a Free ConsultationEnvironment Variable Management
Never hardcode secrets in settings.py or commit them to version control. Use an environment file that systemd loads automatically.
# /srv/projects/myapp/.env
DJANGO_SECRET_KEY='your-50-char-random-string-here'
DATABASE_URL='postgres://myapp:password@localhost:5432/myapp'
ALLOWED_HOSTS='yourdomain.com,www.yourdomain.com'
REDIS_URL='redis://127.0.0.1:6379/0'
EMAIL_HOST_PASSWORD='smtp-password'
SENTRY_DSN='https://[email protected]/project'
# Permissions: readable only by the app user
# sudo chown www-data-app:www-data-app /srv/projects/myapp/.env
# sudo chmod 600 /srv/projects/myapp/.env
The chmod 600 ensures only the application user can read the file — not other users on the system, not web visitors through a directory traversal vulnerability. Generate DJANGO_SECRET_KEY with python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())".
Zero-Downtime Deploy Script
A deploy script that minimizes downtime follows this sequence: transfer code, install dependencies, run migrations, collect static files, and gracefully reload the application server.
#!/bin/bash
set -e
PROJECT=/srv/projects/myapp
APP=$PROJECT/myapp
VENV=$PROJECT/venv
echo "=== Deploying ==="
# 1. Transfer code (git archive avoids deploying .git, .venv, etc.)
cd /local/path/to/myapp
git archive HEAD | ssh myserver "cd $APP && sudo -u www-data-app tar xf -"
# 2. Install any new dependencies
ssh myserver "sudo -u www-data-app $VENV/bin/pip install -q -r $APP/requirements.txt"
# 3. Run migrations
ssh myserver "cd $APP && sudo -u www-data-app env DJANGO_ENV=production $VENV/bin/python manage.py migrate --noinput"
# 4. Collect static files
ssh myserver "cd $APP && sudo -u www-data-app env DJANGO_ENV=production $VENV/bin/python manage.py collectstatic --noinput --clear"
# 5. Graceful reload (zero downtime)
ssh myserver "sudo systemctl reload myapp"
echo "=== Deploy complete ==="
The key to zero downtime is systemctl reload instead of restart. Reload sends SIGHUP to Gunicorn's master process, which spawns new workers with the updated code and gracefully shuts down old workers after they finish serving their current requests. No request is dropped during the transition. For performance-optimized Django sites, also run npm run build for Vite/Tailwind assets before collecting static files.
Log Rotation
Without log rotation, your log files grow until they fill the disk. Configure logrotate to manage Gunicorn logs:
# /etc/logrotate.d/myapp
/srv/projects/myapp/logs/*.log {
daily
rotate 14
compress
delaycompress
missingok
notifempty
create 0640 www-data-app www-data-app
postrotate
systemctl reload myapp > /dev/null 2>&1 || true
endscript
}
This rotates logs daily, keeps 14 days of history, compresses old logs, and signals Gunicorn to reopen log files after rotation. The delaycompress option keeps the most recently rotated file uncompressed for easy debugging — you can tail yesterday's log without decompressing it first.
Security Hardening Checklist
Beyond the systemd hardening directives, apply these server-level security measures before going live.
- SSH: Key-only authentication (disable PasswordAuthentication in sshd_config). Change the SSH port from 22 to a non-standard port to reduce automated scanning noise. Use fail2ban to block repeated failed login attempts.
- Firewall:
ufw allow 80,443/tcpandufw allow YOUR_SSH_PORT/tcp. Deny everything else. Do not expose PostgreSQL (5432) or Redis (6379) to the internet. - Django settings: Ensure
DEBUG = False,SECURE_SSL_REDIRECT = True,SESSION_COOKIE_SECURE = True,CSRF_COOKIE_SECURE = True, andSECURE_HSTS_SECONDS = 63072000. Runpython manage.py check --deployand fix every warning. - Database: Use a strong password for the PostgreSQL user. Configure
pg_hba.confto allow connections only from localhost. Run regular backups withpg_dumpvia cron — daily at minimum, hourly if data changes frequently. - Automatic updates: Enable unattended-upgrades for security patches:
sudo apt install unattended-upgrades && sudo dpkg-reconfigure -plow unattended-upgrades. - Monitoring: Set up Sentry for application error tracking and UptimeRobot (or similar) for uptime monitoring. Know when your site goes down before your users do.
This deployment stack — Gunicorn behind Nginx with systemd management — is the standard for production Django applications. It runs reliably for years with minimal maintenance, handles traffic spikes through Gunicorn's worker model, and recovers automatically from application crashes through systemd's restart policy. For more complex deployments involving multi-tenant applications or SaaS platforms with billing, the same foundation applies with additional configuration for tenant routing and background task processing. If you need help deploying or optimizing your Django application, our Django development service includes deployment setup as a standard deliverable.
Related reading: Why Django 6.1 Is Perfect for SaaS MVPs in 2027 · Third-Party API Integration Patterns for Django Applications · React vs Django Templates: When to Add a JavaScript Frontend



Frequently asked questions
Is Django still a good choice for web development in 2027?
Yes. Django's batteries-included approach — authentication, ORM, admin, migrations, security middleware — makes it the most productive framework for business applications. Django 6.1 added composite primary keys, generated fields, and improved async support. The ecosystem continues growing with over 5,000 packages on PyPI.
When should I choose Django over Node.js or Next.js?
Choose Django when your application is data-heavy, needs a robust admin interface, requires complex business logic, or when your team knows Python. Choose Node.js/Next.js when you need server-side rendering for a React frontend, real-time features are the core product, or your team is JavaScript-first.
How do I deploy a Django application to production?
The standard production stack is: Gunicorn (application server) behind Nginx (reverse proxy), PostgreSQL (database), Redis (caching and sessions), systemd (process management), and Cloudflare or Let's Encrypt (HTTPS). Use environment variables for secrets and split settings into base, dev, and production files.
Full-stack developer specializing in Django, AI automation, and Google Ads management. Building production SaaS platforms and custom web applications for businesses across the US.