Django's development server (runserver) is explicitly not meant for production: it is single-process, unoptimised and not hardened. A production deployment needs a WSGI server to run your code, a web server to handle TLS and static files, a real database, and settings that are safe to expose to the internet. This guide sets all of that up on Ubuntu 24.04 or Debian 12, using Gunicorn, Nginx, PostgreSQL and systemd.
How the Pieces Fit Together
Browser ──HTTPS──▶ Nginx :443 ──▶ /static/, /media/ (files served directly)
└──────▶ Gunicorn 127.0.0.1:8000 ──▶ Django ──▶ PostgreSQL
- Gunicorn runs several Django worker processes. It speaks WSGI to Django and HTTP to Nginx.
- Nginx handles HTTPS, buffers slow clients and serves static assets far more efficiently than Python can.
- systemd keeps Gunicorn running, restarts it after failures and starts it at boot.
If your project uses async views or Django Channels (WebSockets), run it under an ASGI server such as Uvicorn instead; the Nginx and systemd parts below stay almost the same. Our FastAPI deployment guide shows the Uvicorn variant.
Step 1: Install System Packages and Create a User
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3 python3-venv python3-dev build-essential \
libpq-dev postgresql nginx git
sudo adduser --system --group --home /srv/django django
The dedicated django user owns the code and runs Gunicorn, so the application never runs as root.
Step 2: Create the PostgreSQL Database
sudo -u postgres psql <<'SQL'
CREATE USER mysite WITH PASSWORD 'use-a-long-random-password';
CREATE DATABASE mysite OWNER mysite;
SQL
PostgreSQL listens only on localhost by default on Ubuntu and Debian, which is what you want when Django runs on the same server. Keep port 5432 closed in the firewall.
Step 3: Deploy the Code and Virtual Environment
sudo -u django git clone https://github.com/your-org/mysite.git /srv/django/mysite
sudo -u django python3 -m venv /srv/django/venv
sudo -u django /srv/django/venv/bin/pip install --upgrade pip
sudo -u django /srv/django/venv/bin/pip install -r /srv/django/mysite/requirements.txt gunicorn "psycopg[binary]"
psycopg (version 3) is the current PostgreSQL adapter and is supported by Django 4.2 and later; psycopg2 also still works. Pin all versions in requirements.txt.
Step 4: Production Settings
Read secrets and host-specific values from the environment rather than hard-coding them. A minimal production section of settings.py:
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = False
ALLOWED_HOSTS = ["example.com", "www.example.com"]
CSRF_TRUSTED_ORIGINS = ["https://example.com", "https://www.example.com"]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "mysite",
"USER": "mysite",
"PASSWORD": os.environ["DB_PASSWORD"],
"HOST": "127.0.0.1",
"PORT": "5432",
"CONN_MAX_AGE": 60,
}
}
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"
# Nginx terminates HTTPS and tells Django via this header
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
Notes on the settings people most often get wrong:
DEBUG = Falseis mandatory. WithDEBUG = True, error pages leak settings, SQL queries and file paths.CSRF_TRUSTED_ORIGINSmust include the scheme (https://) in Django 4.0 and later; otherwise POST requests over HTTPS fail with a 403.SECURE_PROXY_SSL_HEADERis only safe because Nginx always sets (and overwrites)X-Forwarded-Proto. Never enable it if the app is reachable without the proxy.
Create the environment file that systemd will load:
sudo tee /srv/django/.env >/dev/null <<'EOF'
DJANGO_SECRET_KEY=replace-with-50-plus-random-characters
DB_PASSWORD=use-a-long-random-password
DJANGO_SETTINGS_MODULE=mysite.settings
EOF
sudo chown django:django /srv/django/.env
sudo chmod 600 /srv/django/.env
Generate a secret key with python3 -c "import secrets; print(secrets.token_urlsafe(64))".
Step 5: Migrate, Collect Static Files and Check
cd /srv/django/mysite
sudo -u django bash -c 'set -a; . /srv/django/.env; set +a; \
/srv/django/venv/bin/python manage.py migrate && \
/srv/django/venv/bin/python manage.py collectstatic --noinput && \
/srv/django/venv/bin/python manage.py check --deploy'
check --deploy lists security settings you have missed, such as HSTS or secure cookies. Fix the warnings that apply to you before launch. Create an admin account with manage.py createsuperuser the same way.
Step 6: Run Gunicorn with systemd
Create /etc/systemd/system/django.service:
[Unit]
Description=Gunicorn for mysite
After=network.target postgresql.service
[Service]
User=django
Group=django
WorkingDirectory=/srv/django/mysite
EnvironmentFile=/srv/django/.env
ExecStart=/srv/django/venv/bin/gunicorn mysite.wsgi:application \
--bind 127.0.0.1:8000 \
--workers 3 \
--timeout 30 \
--access-logfile - --error-logfile -
Restart=always
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now django
sudo systemctl status django
curl -I -H "Host: example.com" http://127.0.0.1:8000/
How many workers? Gunicorn's documentation suggests (2 × CPU cores) + 1 as a starting point for synchronous workers, so 5 on a 2 vCore server. Each worker loads your whole project into memory, so check free -h and reduce the count if RAM is tight. Measure under realistic load rather than guessing.
Step 7: Configure Nginx
Create /etc/nginx/sites-available/mysite:
server {
listen 80;
server_name example.com www.example.com;
client_max_body_size 20m;
location /static/ {
alias /srv/django/mysite/staticfiles/;
expires 30d;
access_log off;
}
location /media/ {
alias /srv/django/mysite/media/;
}
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_redirect off;
}
}
sudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
sudo ufw allow 'Nginx Full'
Note the trailing slashes on both location /static/ and alias .../staticfiles/; a mismatch is the most common cause of 404s for CSS and JavaScript. Nginx (running as www-data) also needs read access to those directories: sudo chmod 755 /srv/django /srv/django/mysite is usually enough because the files themselves are world-readable.
Never let Nginx serve uploaded media from a directory where users could upload executable content to another app, and validate file types in Django.
Step 8: Enable HTTPS
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
sudo certbot --nginx -d example.com -d www.example.com
sudo certbot renew --dry-run
After HTTPS works, consider SECURE_HSTS_SECONDS in Django (start small, for example 3600) and raise it once you are confident. The full certificate walkthrough is in our Let's Encrypt guide.
Background Tasks and Scheduled Jobs
Do not run slow work (sending email, generating reports, calling external APIs) inside the request. Two common patterns:
- Celery with Redis for queued tasks. Run the worker as its own systemd service, for example
celery -A mysite worker --concurrency 2, and Celery beat (or cron) for schedules. - Management commands on a schedule for simple periodic jobs. See our cron guide for the environment pitfalls.
Step 9: A Repeatable Update Process
#!/usr/bin/env bash
# /srv/django/deploy.sh (run as root or via sudo)
set -euo pipefail
cd /srv/django/mysite
sudo -u django git pull --ff-only
sudo -u django /srv/django/venv/bin/pip install -r requirements.txt
sudo -u django bash -c 'set -a; . /srv/django/.env; set +a; \
/srv/django/venv/bin/python manage.py migrate --noinput && \
/srv/django/venv/bin/python manage.py collectstatic --noinput'
systemctl reload django 2>/dev/null || systemctl restart django
Gunicorn performs a graceful reload on HUP; add ExecReload=/bin/kill -s HUP $MAINPID to the service so systemctl reload django replaces workers without dropping connections. Always back up the database before running migrations that alter or drop columns.
SkyRainCloud Plans for This Workload
A Django site with PostgreSQL on the same server fits the 2 vCore / 8 GB plans. Add Celery workers, Redis or heavier traffic and the 4 vCore / 16 GB tier gives Gunicorn and the database room to breathe.
AMD EPYC 7C13 VPS
Dedicated KVM vCores on AMD EPYC 7C13 (up to 3.70 GHz) with DDR4 ECC memory, NVMe SSD and an unmetered 1 Gbps port.
| Plan | vCores | RAM | Storage | Network | Price | Good for | Buy |
|---|---|---|---|---|---|---|---|
| VPS 1 — AMD | 2 | 8 GB DDR4 ECC | 40 GB NVMe SSD | 1 Gbps, unmetered | ₹649/month | Websites, small APIs, bots, staging and VPN servers | Order |
| VPS 2 — AMD | 4 | 16 GB DDR4 ECC | 80 GB NVMe SSD | 1 Gbps, unmetered | ₹1,299/month | WooCommerce, Node.js/Python backends, Docker Compose stacks, CI runners | Order |
| VPS 3 — AMD | 8 | 32 GB DDR4 ECC | 150 GB NVMe SSD | 1 Gbps, unmetered | ₹2,499/month | Production databases, high-traffic sites, multi-container apps | Order |
| VPS 4 — AMD | 16 | 64 GB DDR4 ECC | 250 GB NVMe SSD | 1 Gbps, unmetered | ₹4,899/month | Large production workloads, SaaS platforms, analytics, in-memory caches | Order |
Intel Xeon Platinum 8269CY VPS
KVM VPS on Intel Xeon Platinum 8269CY (up to 3.80 GHz Turbo) with DDR4 ECC memory, NVMe SSD, full root access and an unmetered 1 Gbps port.
| Plan | vCores | RAM | Storage | Network | Price | Good for | Buy |
|---|---|---|---|---|---|---|---|
| VPS 1 — Intel | 2 | 8 GB DDR4 ECC | 40 GB NVMe SSD | 1 Gbps, unmetered | ₹649/month | Business websites, small apps, scheduled jobs and bots | Order |
| VPS 2 — Intel | 4 | 16 GB DDR4 ECC | 80 GB NVMe SSD | 1 Gbps, unmetered | ₹1,169/month | Business software, mid-size databases, several sites on one server | Check stock |
| VPS 3 — Intel | 8 | 32 GB DDR4 ECC | 150 GB NVMe SSD | 1 Gbps, unmetered | ₹2,249/month | ERP/CRM stacks, heavier databases, multiple production apps | Check stock |
| VPS 4 — Intel | 16 | 64 GB DDR4 ECC | 250 GB NVMe SSD | 1 Gbps, unmetered | ₹4,299/month | High-memory workloads and consolidated production servers | Check stock |
Prices are monthly in INR as listed on the SkyRainCloud store (verified 2026-11-14). Stock and final pricing are shown on the product page at checkout.
Troubleshooting
| Symptom | Cause and fix |
|---|---|
| 400 Bad Request | Domain missing from ALLOWED_HOSTS |
| 403 CSRF verification failed on forms | Add the https:// origin to CSRF_TRUSTED_ORIGINS; make sure Nginx sends X-Forwarded-Proto |
| Site loads without CSS | collectstatic not run, wrong alias path or missing trailing slash, or Nginx cannot read the directory |
| 502 Bad Gateway | Gunicorn not running: journalctl -u django -n 50; often a missing environment variable or import error |
| Redirect loop after HTTPS | SECURE_SSL_REDIRECT = True without SECURE_PROXY_SSL_HEADER, or Cloudflare set to Flexible SSL |
| Workers killed with "WORKER TIMEOUT" | A view runs longer than --timeout; optimise it or move the work to Celery |
Frequently Asked Questions
Can I use runserver in production?
Gunicorn or uWSGI for Django?
How many Gunicorn workers should I run?
(2 × vCores) + 1 for synchronous workers, then check memory: each worker holds a full copy of your project. On a 2 vCore / 8 GB server, 3–5 workers is typical.Why do my static files return 404 in production?
DEBUG = False, Django stops serving static files. Run collectstatic, point Nginx's alias at STATIC_ROOT with matching trailing slashes, and make sure Nginx can read the directory. WhiteNoise is an alternative when you cannot configure a web server.Should PostgreSQL run on the same VPS as Django?
What does manage.py check --deploy do?
DEBUG = True, missing secure cookies or HSTS. Run it on every new deployment.How do I fix CSRF errors after switching to HTTPS?
https://, to CSRF_TRUSTED_ORIGINS, set SECURE_PROXY_SSL_HEADER and make sure Nginx passes X-Forwarded-Proto $scheme.Where do I store the SECRET_KEY?
EnvironmentFile=. Never commit it to Git, and rotate it if it is ever exposed.