Application Hosting15 min read•Updated November 2026

How to Deploy a Django Application on a VPS with Nginx

Quick answer

To deploy Django on a VPS, install Python, PostgreSQL and Nginx, put the project in a virtual environment, set DEBUG = False, ALLOWED_HOSTS and STATIC_ROOT, run collectstatic and migrate, then serve the app with Gunicorn under systemd on 127.0.0.1:8000. Nginx serves /static/ and /media/ directly, proxies everything else to Gunicorn and terminates HTTPS with a Let's Encrypt certificate. Run python manage.py check --deploy before going live.

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 = False is mandatory. With DEBUG = True, error pages leak settings, SQL queries and file paths.
  • CSRF_TRUSTED_ORIGINS must include the scheme (https://) in Django 4.0 and later; otherwise POST requests over HTTPS fail with a 403.
  • SECURE_PROXY_SSL_HEADER is 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.

PlanvCoresRAMStorageNetworkPriceGood forBuy
VPS 1 — AMD28 GB DDR4 ECC40 GB NVMe SSD1 Gbps, unmetered₹649/monthWebsites, small APIs, bots, staging and VPN serversOrder
VPS 2 — AMD416 GB DDR4 ECC80 GB NVMe SSD1 Gbps, unmetered₹1,299/monthWooCommerce, Node.js/Python backends, Docker Compose stacks, CI runnersOrder
VPS 3 — AMD832 GB DDR4 ECC150 GB NVMe SSD1 Gbps, unmetered₹2,499/monthProduction databases, high-traffic sites, multi-container appsOrder
VPS 4 — AMD1664 GB DDR4 ECC250 GB NVMe SSD1 Gbps, unmetered₹4,899/monthLarge production workloads, SaaS platforms, analytics, in-memory cachesOrder

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.

PlanvCoresRAMStorageNetworkPriceGood forBuy
VPS 1 — Intel28 GB DDR4 ECC40 GB NVMe SSD1 Gbps, unmetered₹649/monthBusiness websites, small apps, scheduled jobs and botsOrder
VPS 2 — Intel416 GB DDR4 ECC80 GB NVMe SSD1 Gbps, unmetered₹1,169/monthBusiness software, mid-size databases, several sites on one serverCheck stock
VPS 3 — Intel832 GB DDR4 ECC150 GB NVMe SSD1 Gbps, unmetered₹2,249/monthERP/CRM stacks, heavier databases, multiple production appsCheck stock
VPS 4 — Intel1664 GB DDR4 ECC250 GB NVMe SSD1 Gbps, unmetered₹4,299/monthHigh-memory workloads and consolidated production serversCheck 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

SymptomCause and fix
400 Bad RequestDomain missing from ALLOWED_HOSTS
403 CSRF verification failed on formsAdd the https:// origin to CSRF_TRUSTED_ORIGINS; make sure Nginx sends X-Forwarded-Proto
Site loads without CSScollectstatic not run, wrong alias path or missing trailing slash, or Nginx cannot read the directory
502 Bad GatewayGunicorn not running: journalctl -u django -n 50; often a missing environment variable or import error
Redirect loop after HTTPSSECURE_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?
No. Django's documentation states that the development server is not intended for production use. Use Gunicorn or uWSGI (WSGI), or Uvicorn/Daphne (ASGI), behind Nginx.
Gunicorn or uWSGI for Django?
Both work. Gunicorn is simpler to configure and is the common default; uWSGI has more features and more options to tune. If you need WebSockets or async views, use an ASGI server instead.
How many Gunicorn workers should I run?
Start with (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?
With 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?
For small and medium projects, yes: it is simpler and fast over localhost. Move the database to its own server when it needs dedicated memory, or when you run several application servers.
What does manage.py check --deploy do?
It runs Django's deployment checklist and warns about insecure settings such as DEBUG = True, missing secure cookies or HSTS. Run it on every new deployment.
How do I fix CSRF errors after switching to HTTPS?
Add your full origins, including 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?
In an environment file readable only by the service user (mode 600), loaded with systemd's EnvironmentFile=. Never commit it to Git, and rotate it if it is ever exposed.
How do I run Celery on the same server?
Create a second systemd service for the Celery worker using the same virtual environment and environment file, and install Redis bound to localhost as the broker. Size RAM for Gunicorn workers plus Celery workers plus the database.
Which SkyRainCloud plan suits a Django project?
A typical Django site with PostgreSQL runs well on the 2 vCore / 8 GB AMD EPYC or Intel plan. Choose 4 vCores / 16 GB when you add Celery, Redis or significant traffic, and the larger tiers for busy databases.
Instant UPI • ₹649/mo
Fast KVM Cloud Provisioning