Short answer: To deploy a Django app on a VPS, run Gunicorn under systemd behind Nginx, keep data in PostgreSQL, let Nginx serve the collected static files and add a free Let's Encrypt certificate with certbot. On Ubuntu 24.04 or 26.04 the setup takes about an hour on a 1–2 GB server; 2 GB plans start at $1.85 a month.
This guide shows how to deploy a Django app on a VPS the way most production sites run it: Gunicorn as the application server under systemd, Nginx in front as a reverse proxy, PostgreSQL for data, static and media files served by Nginx, and a free Let's Encrypt certificate from certbot. Every command works on Ubuntu 24.04 LTS and Ubuntu 26.04 LTS.
The result survives reboots, reloads new code without dropping requests and passes manage.py check --deploy. Budget about an hour. The last sections cover logs and the four errors behind most "it worked locally" threads: 502 Bad Gateway, missing static files, DisallowedHost and CSRF origin failures.
Before you deploy a Django app on a VPS
You need a VPS with root SSH access, a domain whose A record points to the server, and a Django project in Git with a requirements.txt. The examples use example.com, a project package called myproject and a user called deploy. If the server is brand new, see how to set up a VPS first.
Pick the Django and Ubuntu versions
Django 6.1, released on August 5, 2026, is the current feature release, with security fixes until December 2027. Django 5.2 is the long-term support (LTS) release, with security fixes until April 2028; the next LTS, 6.2, is due in April 2027. Both Ubuntu LTS releases ship a system Python that Django 6.1 supports.
| Component | Ubuntu 24.04 LTS | Ubuntu 26.04 LTS | Why it matters |
|---|---|---|---|
Python (python3) |
3.12 | 3.14 | Django 6.1 supports Python 3.12, 3.13 and 3.14 |
PostgreSQL (postgresql package) |
16 | 18 | Django 6.1 needs PostgreSQL 15 or newer |
| Standard support ends | April 2029 | April 2031 | Ubuntu Pro extends both |
sudo implementation |
classic sudo | sudo-rs | The commands below work on both |
If you stay on Django 5.2 LTS, check its Python compatibility table in Django's install FAQ before you pick 26.04 and its Python 3.14.
How big a Django VPS do you need?
Django publishes no hardware requirements. Plan on 1 to 2 GB of RAM for the app, PostgreSQL and a few Gunicorn workers on one machine, more with Celery or Redis. Across the 199 providers we track, the cheapest 2 GB plan costs $1.85 a month and the median provider's cheapest costs $10.00 (see the 2 GB VPS comparison).
As of November 30, 2026, these are the top five plans in our best VPS for Django ranking:
| # | Provider | Plan | Specs | Price / month | Locations |
|---|---|---|---|---|---|
| 1 | LikeVPS | Lite | 1 vCPU, 1 GB RAM, 25 GB NVMe, unmetered traffic | $9.50 | 26 |
| 2 | netcup | VPS piko G11s | 1 vCPU, 1 GB RAM, 30 GB SSD, unmetered traffic | $2.07 prepaid annually or longer | 5 |
| 3 | Hosteons | Gigabit KVM VPS 1 | 1 vCPU, 1 GB RAM, 10 GB SSD, 1 TB traffic | $1.75 prepaid annually or longer | 8 |
| 4 | AlphaVPS | C2G | 2 vCPU, 2 GB RAM, 30 GB NVMe, 3 TB traffic | $3.33 | 7 |
| 5 | SolidVPS (formerly SolidSEOVPS) | SBudgetSSD4G | 2 vCPU, 4 GB RAM, 40 GB SSD, 2 TB traffic | $3.33 | 21 |
Top 5 of 196 providers in our Best VPS for Django ranking, updated November 30, 2026. Each plan meets the software's published minimum requirements.
Step 1: Create a deploy user and lock down SSH
Log in as root once, create an unprivileged user and give it your SSH key. An app running as root hands the whole server to anyone who exploits a bug in it.
adduser deploy
usermod -aG sudo deploy
rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
Open a second terminal and confirm that ssh deploy@your-server-ip works and that sudo -v accepts the password. Then turn off password and root logins:
sudo tee /etc/ssh/sshd_config.d/00-hardening.conf > /dev/null <<'EOF'
PasswordAuthentication no
PermitRootLogin no
EOF
sudo sshd -t && sudo systemctl restart ssh
The 00- prefix matters: OpenSSH keeps the first value it reads for each option, and some cloud images ship a 50-cloud-init.conf that re-enables passwords. Our VPS security checklist covers fail2ban and automatic updates.
Step 2: Install Python, PostgreSQL and Nginx
Install the system packages from Ubuntu's own archive:
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3-venv git postgresql nginx
Gunicorn and the PostgreSQL driver come from pip in Step 5, inside a virtual environment, so their versions follow your requirements.txt rather than the operating system.
Step 3: Turn on the firewall
UFW ships with Ubuntu Server but is inactive. Allow SSH first, or you will lock yourself out, then HTTP and HTTPS:
sudo ufw allow OpenSSH
sudo ufw allow 80,443/tcp
sudo ufw enable
sudo ufw status verbose
PostgreSQL listens only on localhost by default and Gunicorn will use a Unix socket, so the internet needs only ports 22, 80 and 443. Open the same three in your provider's network firewall, if it has one.
Step 4: Create the PostgreSQL database and user
Open a PostgreSQL shell as the postgres system user:
sudo -u postgres psql
Then create a role and a database that the role owns:
CREATE ROLE myproject WITH LOGIN PASSWORD 'use-a-long-random-password';
ALTER ROLE myproject SET client_encoding TO 'utf8';
ALTER ROLE myproject SET default_transaction_isolation TO 'read committed';
ALTER ROLE myproject SET timezone TO 'UTC';
CREATE DATABASE myproject OWNER myproject;
\q
Ownership matters on PostgreSQL 15 and later. The public schema no longer lets every role create tables, so a role that doesn't own the database gets permission denied for schema public on its first migrate. The three ALTER ROLE lines set the values Django needs on each connection; when they are already the role's defaults, Django skips setting them for every new connection.
Step 5: Clone the code and build a virtual environment
Keep the code, the virtual environment and the collected files under one directory owned by the deploy user:
sudo mkdir -p /srv/myproject
sudo chown deploy:deploy /srv/myproject
cd /srv/myproject
git clone https://github.com/you/myproject.git app
python3 -m venv venv
venv/bin/pip install --upgrade pip
venv/bin/pip install -r app/requirements.txt
mkdir -p static media
For a private repository, add a read-only deploy key to the Git host. Your requirements.txt needs at least these lines (use Django>=5.2,<5.3 to stay on the LTS):
Django>=6.1,<6.2
gunicorn
psycopg[binary]
Pinning the minor series lets pip install pick up security patches without jumping to a new feature release. psycopg 3 is the PostgreSQL driver Django's documentation recommends.
Step 6: Configure production settings with environment variables
Keep secrets out of Git. Put them in one environment file that systemd loads for Gunicorn and that you load in your shell for management commands:
sudo mkdir -p /etc/myproject
sudo tee /etc/myproject/env > /dev/null <<'EOF'
DJANGO_SECRET_KEY=replace-me
DJANGO_DEBUG=False
DJANGO_ALLOWED_HOSTS=example.com,www.example.com
DATABASE_NAME=myproject
DATABASE_USER=myproject
DATABASE_PASSWORD=use-a-long-random-password
EOF
sudo chown root:deploy /etc/myproject/env
sudo chmod 640 /etc/myproject/env
Generate a secret key with Django's own helper and paste it over replace-me:
/srv/myproject/venv/bin/python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
Then read those variables in settings.py. The block below follows Django's deployment checklist:
import os
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = os.environ.get("DJANGO_DEBUG", "False") == "True"
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",")
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": os.environ["DATABASE_NAME"],
"USER": os.environ["DATABASE_USER"],
"PASSWORD": os.environ["DATABASE_PASSWORD"],
"HOST": "localhost",
"PORT": "5432",
"CONN_MAX_AGE": 60,
}
}
STATIC_URL = "static/"
STATIC_ROOT = "/srv/myproject/static"
MEDIA_URL = "media/"
MEDIA_ROOT = "/srv/myproject/media"
# Nginx terminates TLS and sets X-Forwarded-Proto on every request
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 3600 # raise to 31536000 once HTTPS is stable
SECRET_KEY has no default, so a missing variable stops Django at startup instead of running with a guessable key. SECURE_PROXY_SSL_HEADER is safe only because Nginx overwrites X-Forwarded-Proto on every request (Step 9); never set it if clients can reach Gunicorn directly. For email, Django 6.1 uses the new MAILERS setting in place of the EMAIL_* settings; also set DEFAULT_FROM_EMAIL and SERVER_EMAIL.
Now run Django's own audit with the production environment loaded:
cd /srv/myproject/app
set -a; . /etc/myproject/env; set +a
../venv/bin/python manage.py check --deploy
Fix what it reports. security.W008 (SECURE_SSL_REDIRECT not set) is fine to leave, because Nginx does the redirect in Step 10. The HSTS warnings about subdomains and preload are a judgement call for your domain.
Step 7: Run migrations and collect static files
In the same shell, with the environment still loaded:
../venv/bin/python manage.py migrate
../venv/bin/python manage.py collectstatic --noinput
../venv/bin/python manage.py createsuperuser
collectstatic copies every app's static files, including the admin's CSS, into STATIC_ROOT, where Nginx will serve them. With DEBUG = False, Django doesn't serve static files at all.
Step 8: Run Gunicorn under systemd
Gunicorn's deployment docs use two systemd units: a socket unit that owns /run/gunicorn.sock and a service unit that runs Gunicorn. Because systemd holds the socket open, connections wait in its queue during a restart instead of failing. Create the socket unit first:
# /etc/systemd/system/gunicorn.socket
[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
SocketUser=www-data
SocketGroup=www-data
SocketMode=0660
[Install]
WantedBy=sockets.target
Then the service unit:
# /etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon for myproject
Requires=gunicorn.socket
After=network.target
[Service]
Type=notify
NotifyAccess=main
User=deploy
Group=deploy
WorkingDirectory=/srv/myproject/app
EnvironmentFile=/etc/myproject/env
ExecStart=/srv/myproject/venv/bin/gunicorn --workers 3 --access-logfile - myproject.wsgi:application
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true
[Install]
WantedBy=multi-user.target
The socket belongs to www-data, the user Nginx runs as, while the workers run as deploy. Gunicorn suggests (2 × CPU cores) + 1 workers as a starting point, which is 3 on a 1-vCPU VPS. Enable the socket and test it before Nginx is involved:
sudo systemctl daemon-reload
sudo systemctl enable --now gunicorn.socket
sudo curl -sI --unix-socket /run/gunicorn.sock -H "Host: example.com" http://localhost/
The first request starts gunicorn.service. Expect HTTP/1.1 200 OK, or a 302 if the home page requires a login. A 400 means the Host header doesn't match ALLOWED_HOSTS.
Step 9: Configure Nginx as the reverse proxy
Create /etc/nginx/sites-available/myproject. The proxy headers come from Gunicorn's documented Nginx example:
upstream app_server {
server unix:/run/gunicorn.sock fail_timeout=0;
}
# Close connections for host names you don't serve
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 444;
}
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
client_max_body_size 20M;
location /static/ {
alias /srv/myproject/static/;
}
location /media/ {
alias /srv/myproject/media/;
}
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect off;
proxy_pass http://app_server;
}
}
Enable the site, remove Ubuntu's default site (it also claims default_server) and reload:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
The return 444 block follows the checklist's advice for ALLOWED_HOSTS: bots that request your bare IP address get the connection closed by Nginx and never reach Django. Uploaded media is untrusted input; Nginx serves it as plain files and never executes it. client_max_body_size raises the upload limit from Nginx's 1 MB default.
Step 10: Add HTTPS with Let's Encrypt and certbot
Certbot's developers recommend the snap package, which stays current and installs its own renewal timer:
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
sudo certbot --nginx --redirect -d example.com -d www.example.com
sudo certbot renew --dry-run
Certbot adds listen 443 ssl, the certificate paths and an HTTP-to-HTTPS redirect to your server block. Open https://example.com/admin/, log in and check that the admin has its CSS. Ubuntu also packages certbot (python3-certbot-nginx), but that build lags behind upstream releases. Once HTTPS has worked for a few days, raise SECURE_HSTS_SECONDS.
Step 11: Deploy updates without downtime
Gunicorn reloads gracefully on SIGHUP: the master starts new workers with the new code, then stops the old workers once they finish their requests. The socket never closes, so Nginx never sees a refused connection. This works because Gunicorn doesn't preload the app by default; with --preload, a reload no longer picks up new code. Put the release steps in /srv/myproject/deploy.sh:
#!/usr/bin/env bash
set -euo pipefail
cd /srv/myproject/app
git pull --ff-only
../venv/bin/pip install -r requirements.txt
set -a; . /etc/myproject/env; set +a
../venv/bin/python manage.py migrate --noinput
../venv/bin/python manage.py collectstatic --noinput
sudo systemctl reload gunicorn
Make it executable with chmod +x, then let the deploy user run that one privileged command without a password:
echo 'deploy ALL=(root) NOPASSWD: /usr/bin/systemctl reload gunicorn' | sudo tee /etc/sudoers.d/deploy-gunicorn
sudo chmod 440 /etc/sudoers.d/deploy-gunicorn
sudo visudo -c
Two rules keep reloads free of downtime. First, migrate runs while the old code is still serving, so each migration must work with both versions: add a nullable column in one release and drop the old one in the next. Second, systemctl restart stops every worker before starting new ones. Use it only after changing the unit file (run daemon-reload first) or the environment file, which a reload doesn't re-read.
Where to find the logs
Most problems show up in one of these places:
| What | Where to look |
|---|---|
| Gunicorn and Django output | journalctl -u gunicorn -f |
| Socket and service state | systemctl status gunicorn.socket gunicorn |
| Nginx errors, including every 502 | /var/log/nginx/error.log |
| Nginx requests | /var/log/nginx/access.log |
| PostgreSQL | /var/log/postgresql/postgresql-16-main.log (18 on Ubuntu 26.04) |
| Out-of-memory kills | journalctl -k --grep=oom |
With DEBUG = False, Django's default logging sends errors only to the ADMINS by email and prints nothing to the console. Add a console handler so tracebacks reach the journal:
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {"console": {"class": "logging.StreamHandler"}},
"root": {"handlers": ["console"], "level": "WARNING"},
}
At WARNING you also see 404s and DisallowedHost reports. Gunicorn's access log lands in the same journal because of --access-logfile -.
Common errors and how to fix them
These four errors account for most first-deploy problems, and each leaves a clear line in the logs above.
502 Bad Gateway
Nginx returns 502 when it gets no usable response from Gunicorn. The reason is in /var/log/nginx/error.log:
connect() to unix:/run/gunicorn.sock failed (2: No such file or directory): the socket unit isn't running, or theupstreampath differs fromListenStream. Runsudo systemctl enable --now gunicorn.socketand compare the two paths.(13: Permission denied): Nginx can't open the socket.SocketUserandSocketGroupmust match the Nginx user,www-dataon Ubuntu.(111: Connection refused): Gunicorn fails at startup.journalctl -u gunicorn -n 50usually shows aModuleNotFoundErrorfrom a wrongWorkingDirectoryor module name, or aKeyErrorfor a missing environment variable.upstream prematurely closed connection: a worker died mid-request. Look forWORKER TIMEOUTin the Gunicorn journal (the default timeout is 30 seconds; raise--timeoutor move slow work to a task queue) or for an out-of-memory kill in the kernel log.
Static files return 404 (admin without CSS)
If pages load but the admin has no styling, Nginx isn't finding the files. Check, in order: that collectstatic ran and /srv/myproject/static/admin/ exists; that the location /static/ prefix matches STATIC_URL; that both the location and the alias path end with a slash; and that www-data can read the directory (a 403 instead of a 404 points to permissions). Templates must build URLs with the static tag, never hard-coded paths:
{% load static %}
<link rel="stylesheet" href="{% static 'css/site.css' %}">
DisallowedHost: Invalid HTTP_HOST header
With DEBUG = False, a request whose Host header isn't in ALLOWED_HOSTS gets 400 Bad Request and a log line such as Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS. Add the exact host names, with no scheme or port, to DJANGO_ALLOWED_HOSTS, check for spaces after the commas, and run sudo systemctl restart gunicorn. Reports for random IPs come from scanners; the return 444 server stops them on port 80, though some still arrive over HTTPS.
CSRF verification failed: Origin checking failed
A 403 page that says "CSRF verification failed" with the reason Origin checking failed - https://example.com does not match any trusted origins. usually means Django thinks the request came over plain HTTP. Since Django 4.0, the CSRF check compares the browser's Origin header with the scheme and host Django sees. Nginx terminates TLS and talks plain HTTP to Gunicorn, so without help Django expects http://example.com and the check fails. The fix is the pair from Steps 6 and 9: proxy_set_header X-Forwarded-Proto $scheme; in Nginx and SECURE_PROXY_SSL_HEADER in settings, followed by sudo systemctl reload gunicorn.
Add an origin to CSRF_TRUSTED_ORIGINS only for real cross-origin requests, for example a front end on app.example.com posting to api.example.com. Entries need the scheme: CSRF_TRUSTED_ORIGINS = ["https://app.example.com"].
Other ways to deploy Django: Docker, ASGI or a self-hosted PaaS
The Gunicorn and Nginx setup above is the most common pattern. Three alternatives come up often:
- Docker. Run an image with your code and Gunicorn under Docker Compose, next to PostgreSQL and a proxy such as Nginx or Caddy. You get identical environments in development and production, and you take on image builds, volumes and container updates. See the Docker VPS ranking.
- ASGI with Uvicorn. For async views, WebSockets or Django Channels, serve
myproject.asgi:application. Django's docs cover Daphne, Hypercorn and Uvicorn. Gunicorn can manage Uvicorn workers (-k uvicorn_worker.UvicornWorker, from theuvicorn-workerpackage), so the systemd and Nginx setup barely changes. - A self-hosted PaaS. Coolify and Dokploy give you git-push deploys, automatic HTTPS and scheduled database backups from a dashboard, but each needs about 2 GB of RAM for itself. Our Coolify vs Dokploy comparison covers how they differ.
Next steps after your first deploy
Set up backups before you need them: a nightly pg_dump copied off the server, plus a provider snapshot before system upgrades (see snapshots vs backups). Turn on unattended security updates, add an external uptime check and test one restore. When the app outgrows one server, move PostgreSQL to its own machine first; the settings only need a new HOST. To compare providers, use the Django VPS ranking or the list of Ubuntu VPS providers.
Frequently asked questions
Do I need Docker to deploy Django on a VPS?
No. Gunicorn under systemd behind Nginx runs Django directly on the host, and on a single server it is easier to debug. Docker pays off when you want the same image in development, CI and production, or several apps with conflicting dependencies on one machine. See the Docker VPS ranking if you go that way.
How much RAM does a Django VPS need?
Django publishes no minimum. A server running Nginx, PostgreSQL and three Gunicorn workers for a small site generally fits in 1 to 2 GB; add memory for Celery, Redis or image processing. As of November 30, 2026, 2 GB plans start at $1.85 a month. Compare plans in the best VPS for Django ranking.
Should I use Django 6.1 or Django 5.2 LTS?
Django 6.1 is the current feature release and gets security fixes until December 2027. Django 5.2 LTS gets security fixes until April 2028. New projects can start on 6.1 and move to the 6.2 LTS after its April 2027 release. Sites that upgrade only from one LTS to the next can stay on 5.2.
Can I use SQLite in production on a VPS?
For a small, mostly read-only site on one server, yes: Django 6.1 supports SQLite 3.37 and later. SQLite allows one writer at a time, though, and backing up a live database file needs care. PostgreSQL handles concurrent writes from several Gunicorn workers and has standard dump and restore tools, so it is the safer default.
How many Gunicorn workers should I run?
Gunicorn's documentation suggests (2 × CPU cores) + 1 as a starting point, which is 3 workers on 1 vCPU and 5 on 2 vCPUs. Each sync worker is a separate process that handles one request at a time, so check memory use after you change the count and lower it if the server starts swapping.
Sources
Commands and requirements were checked against these pages on November 30, 2026. Prices and plan tables in the article come from our provider data, updated the same day.