Django Deployment — From `manage.py runserver` to Production on Ubuntu

Take a Django project from runserver to a real Ubuntu server with Gunicorn, Nginx, PostgreSQL and free HTTPS, explained step by step for a first deployment.

A Mohammed Habib Sep 01, 2026 16 min read 276 views Updated Oct 24, 2026
Cover for Django Deployment — From `manage.py runserver` to Production on Ubuntu

In this guide you'll take a Django project from manage.py runserver on your laptop to a real site on an Ubuntu server, with HTTPS, a proper database and a process that restarts itself. I deployed dirazi.online this way on a single Ubuntu 24.04 box, and the same steps work for any small Django site.

runserver is fine for development. Django's own docs say not to use it in production: it hasn't been through security audits or performance tests, it handles one thing at a time, and nothing restarts it when it crashes. Below we replace it with Gunicorn, Nginx, PostgreSQL and a free Let's Encrypt certificate.

What you need

  • A server running Ubuntu 24.04 LTS that you can reach over SSH (a cheap VPS or a box at home with a public IP).
  • A domain name with an A record pointing at the server's public IP. I'll use example.com and www.example.com in the examples.
  • A Django project in a Git repository, with a requirements.txt.
  • Basic comfort with the Linux terminal: cd, editing files with nano, running commands with sudo.

The pieces, in plain words

Stack Django 6.0 + Gunicorn + Nginx + PostgreSQL
Platform Ubuntu 24.04 LTS
Domain example.com (Let's Encrypt SSL)
Python 3.12 or newer (Django 6.0 needs 3.12+)
Process Manager systemd (socket-activated Gunicorn)
Static Files Collected to staticfiles/, served by Nginx

A few terms you'll see throughout:

  • Gunicorn is a Python web server. It runs several copies ("workers") of your Django app so it can answer many requests at once.
  • Nginx is a fast general-purpose web server. Here it acts as a reverse proxy: it receives every request from the internet first, serves static files itself, and passes everything else to Gunicorn.
  • systemd is the program on Ubuntu that starts, stops and restarts background services.
  • A unix socket is a file that two programs on the same machine use to talk to each other, like a local network port without the network.
  • Static files are the CSS, JavaScript and images that ship with your code. Media files are files your users upload.

How a request flows

CALL FLOW
Django PostgreSQL (localhost Redis (localhost
5432)
6379, optional)

What changes compared to runserver

Issue runserver Production
Concurrency One request at a time by design Multi-worker (Gunicorn)
Static files Python serves them Nginx serves them
HTTPS None Let's Encrypt + Nginx
Process management Manual systemd auto-restart
Error logging stdout only journald and log files
Long-running workers Never recycled Workers recycled after N requests
PACKET ANALYSIS
Server
Ubuntu 24.04 LTS (minimal install)
Web Server
Nginx 1.24 (reverse proxy + static files)
App Server
Gunicorn 23.0 (WSGI, unix socket)
Framework
Django 6.0
Database
PostgreSQL 16
Python
3.12+ (venv)
SSL
Let's Encrypt (certbot)
Process Manager
systemd

Step 0: Prepare the server

Install the packages

Log in to the server with your normal admin account and run:

# Update system
sudo apt update && sudo apt upgrade -y

# Install essentials
sudo apt install -y python3 python3-pip python3-venv \
  python3-dev libpq-dev postgresql postgresql-contrib \
  nginx certbot python3-certbot-nginx \
  git curl ufw

Check it worked: python3 --version should print 3.12 or newer, and systemctl status nginx should say active (running).

Create a deploy user

Never run Django as root. If the app gets compromised, the attacker only gets what this user can touch.

sudo adduser deploy
sudo usermod -aG sudo deploy

adduser asks you for a password. Give it a strong one. The original version of this guide created the user with --disabled-password, but then sudo can't work for that user, because sudo asks for the password that doesn't exist.

Turn on the firewall

UFW (Uncomplicated Firewall) is Ubuntu's front end for the kernel firewall. We allow SSH so you don't lock yourself out, plus HTTP and HTTPS for Nginx:

sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable

Check it: sudo ufw status should list OpenSSH and Nginx Full as ALLOW.

Step 1: Set up PostgreSQL

PostgreSQL is the database. Open its shell as the postgres system user:

sudo -u postgres psql

Your prompt changes to postgres=#. Type these SQL lines (change the password):

CREATE DATABASE myproject;
CREATE USER myprojectuser WITH PASSWORD 'secure_password_here';
ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';
ALTER ROLE myprojectuser SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;
ALTER DATABASE myproject OWNER TO myprojectuser;
\q

The ALTER DATABASE ... OWNER line is new compared to older tutorials. Since PostgreSQL 15, ordinary users can no longer create tables in the public schema by default, so without it python manage.py migrate fails with permission denied for schema public. Making your user the owner of the database fixes that.

Check it worked:

psql -h localhost -U myprojectuser -d myproject -c 'SELECT 1;'

It asks for the password and prints a one-row table.

Step 2: Set up the Django project

Get the code and a virtual environment

A virtual environment (venv) is a private folder of Python packages for one project, so it doesn't clash with the system's Python.

# Switch to deploy user
sudo su - deploy

# Clone your repo
git clone https://github.com/yourusername/yourproject.git
cd yourproject

# Create venv
python3 -m venv env
source env/bin/activate

# Install dependencies
pip install -r requirements.txt
pip install gunicorn psycopg2-binary

Your prompt now starts with (env). Check it: gunicorn --version prints a version number.

Keep secrets out of the code

Your SECRET_KEY and database password must not live in Git. Put them in a file that only the deploy user can read:

nano /home/deploy/.env
# /home/deploy/.env (never commit this)
DJANGO_SECRET_KEY=your-50-char-random-secret-key
DJANGO_SETTINGS_MODULE=config.settings
DJANGO_DB_PASSWORD=secure_password_here

Generate a real secret key with:

python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"

Then lock the file down:

chmod 600 /home/deploy/.env

To load these variables into your current shell before running manage.py:

set -a; source /home/deploy/.env; set +a

systemd will load the same file for Gunicorn in Step 3.

Production settings

Edit config/settings.py (your settings module may live under a different folder name):

# config/settings.py

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY
DEBUG = False
SECRET_KEY = os.environ['DJANGO_SECRET_KEY']
ALLOWED_HOSTS = ['example.com', 'www.example.com', '127.0.0.1']

# Database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'myproject',
        'USER': 'myprojectuser',
        'PASSWORD': os.environ['DJANGO_DB_PASSWORD'],
        'HOST': 'localhost',
        'PORT': '',
    }
}

# Static files
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [BASE_DIR / 'blog' / 'static']

# Media files
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')

# Security headers
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
X_FRAME_OPTIONS = 'DENY'

What the less obvious lines do:

  • os.environ['DJANGO_SECRET_KEY'] crashes on startup if the variable is missing. That's on purpose. A default like 'fallback-key-change-me' would let the site run with a key anyone can read in your repo.
  • ALLOWED_HOSTS lists the domain names Django will answer for. Anything else gets a 400 error.
  • STATICFILES_DIRS points at extra static folders. blog/static is from my project; change or remove it for yours.
  • SECURE_PROXY_SSL_HEADER is needed because Nginx handles HTTPS and talks to Gunicorn over plain HTTP. Without it, Django thinks every request is insecure, SECURE_SSL_REDIRECT sends it to HTTPS, and the browser ends up in an endless redirect loop. Only set it when Nginx (which you control) sits in front of Django.
  • HSTS (SECURE_HSTS_*) tells browsers to only ever use HTTPS for your domain. Django's docs warn that setting it wrong can break your site for as long as the value lasts, here one year. If you're not sure HTTPS works on every subdomain yet, start with SECURE_HSTS_SECONDS = 3600 and leave INCLUDE_SUBDOMAINS and PRELOAD off until you are.

Check your settings load and the database works:

set -a; source /home/deploy/.env; set +a
python manage.py migrate
python manage.py createsuperuser

Step 3: Run Gunicorn with systemd

Test Gunicorn by hand

Still as deploy, inside the project with the venv active:

cd /home/deploy/yourproject
source env/bin/activate

# Test with 3 workers
gunicorn --workers 3 --bind 127.0.0.1:8000 config.wsgi:application

config.wsgi:application means "the application object in config/wsgi.py". From a second SSH session, run curl -I http://127.0.0.1:8000 and you should get an HTTP response (a 301 redirect to HTTPS is expected because of SECURE_SSL_REDIRECT). Press Ctrl+C to stop it.

Don't try binding to unix:/run/gunicorn.sock by hand as deploy: that user can't write to /run. systemd creates that socket for us below.

Gunicorn config file

Create gunicorn_config.py in the project folder:

# gunicorn_config.py
import multiprocessing

bind = "unix:/run/gunicorn.sock"
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = "sync"
timeout = 120
keepalive = 5
max_requests = 1000
max_requests_jitter = 50
accesslog = "/var/log/gunicorn/access.log"
errorlog = "/var/log/gunicorn/error.log"
loglevel = "info"

max_requests restarts each worker after about 1000 requests (the jitter spreads restarts out), which keeps slow memory growth in your app from piling up.

The log folder doesn't exist yet, and Gunicorn refuses to start if it can't write its logs. Create it with your admin account:

sudo mkdir -p /var/log/gunicorn
sudo chown deploy:deploy /var/log/gunicorn

systemd service and socket

Socket activation means systemd creates /run/gunicorn.sock and starts Gunicorn when the first request arrives. Gunicorn picks up the already-open socket.

Create the service file:

sudo nano /etc/systemd/system/gunicorn.service
# /etc/systemd/system/gunicorn.service
[Unit]
Description=Gunicorn daemon for myproject
Requires=gunicorn.socket
After=network.target

[Service]
User=deploy
Group=deploy
WorkingDirectory=/home/deploy/yourproject
EnvironmentFile=/home/deploy/.env
ExecStart=/home/deploy/yourproject/env/bin/gunicorn \
  --config gunicorn_config.py \
  config.wsgi:application
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

EnvironmentFile loads your .env so Django can find DJANGO_SECRET_KEY and the database password.

Then the socket file:

sudo nano /etc/systemd/system/gunicorn.socket
# /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

The socket belongs to www-data, the user Nginx runs as, and mode 0660 means nobody else can use it.

Enable and start

sudo systemctl daemon-reload
sudo systemctl enable gunicorn.socket
sudo systemctl start gunicorn.socket
sudo systemctl enable gunicorn
sudo systemctl start gunicorn

# Check status
sudo systemctl status gunicorn

You want active (running). Test the socket directly:

curl -I --unix-socket /run/gunicorn.sock http://localhost

Any HTTP response means Gunicorn and Django are up. If you get an error, read sudo journalctl -u gunicorn -n 50.

Step 4: Configure Nginx

Collect static files

collectstatic copies every static file from your apps into STATIC_ROOT so Nginx can serve them from one place:

cd /home/deploy/yourproject
source env/bin/activate
set -a; source /home/deploy/.env; set +a
python manage.py collectstatic --noinput

The original guide then copied staticfiles to a second folder. You don't need to: point Nginx straight at /home/deploy/yourproject/staticfiles/. That way a later collectstatic updates the live files without an extra copy step.

Let Nginx into the home folder

On Ubuntu 21.04 and newer, home directories are created with mode 750, so the www-data user can't enter /home/deploy and every static file returns 403. Give Nginx permission to pass through:

sudo chmod 751 /home/deploy

The final 1 lets other users pass through the folder to known paths, but not list what's in it.

First Nginx config (HTTP only)

Nginx won't start if the config points at certificate files that don't exist yet. So we start with a plain HTTP site and let certbot add HTTPS in Step 5.

sudo nano /etc/nginx/sites-available/myproject
# /etc/nginx/sites-available/myproject
server {
    listen 80;
    server_name example.com www.example.com;

    # Static files
    location /static/ {
        alias /home/deploy/yourproject/staticfiles/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Media files
    location /media/ {
        alias /home/deploy/yourproject/media/;
        expires 7d;
    }

    # Gunicorn
    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
        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;
    }

    # Max upload size
    client_max_body_size 20M;
}

alias maps a URL path to a folder on disk. The trailing slashes on both sides matter.

Enable the site

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

nginx -t checks the config for errors before you reload. It should end with test is successful.

Step 5: Add HTTPS with Let's Encrypt

Let's Encrypt gives out free TLS certificates. certbot requests one, proves you own the domain, and edits your Nginx config to use it.

# Get certificate
sudo certbot --nginx -d example.com -d www.example.com

# Verify auto-renewal
sudo certbot renew --dry-run

# Check certbot timer
sudo systemctl status certbot.timer

Choose the redirect option if certbot asks, so plain HTTP visitors get sent to HTTPS. Certificates last 90 days and the certbot.timer renews them automatically.

Check it: open https://example.com in a browser. You should see your site with a padlock, and https://example.com/static/... files should load.

What the finished config looks like

After certbot, your file should look roughly like this. I also add a few security headers by hand in the 443 block:

# /etc/nginx/sites-available/myproject
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    # Security headers
    add_header X-Frame-Options "DENY" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # Static files
    location /static/ {
        alias /home/deploy/yourproject/staticfiles/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Media files
    location /media/ {
        alias /home/deploy/yourproject/media/;
        expires 7d;
    }

    # Gunicorn
    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
        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;
    }

    # Max upload size
    client_max_body_size 20M;
}

Run sudo nginx -t && sudo systemctl reload nginx after any edit.

Step 6: Day-to-day commands

Common commands

Run these as deploy with the venv active and the .env loaded:

# Django shell
python manage.py shell

# Run migrations
python manage.py migrate

# Create superuser
python manage.py createsuperuser

# Collect static files
python manage.py collectstatic --noinput

# Check for issues
python manage.py check --deploy

# View logs
sudo journalctl -u gunicorn -f
sudo tail -f /var/log/nginx/access.log

check --deploy is worth running before you go live. It lists missing security settings such as HSTS, the SSL redirect and secure cookies.

Deploy new code

cd /home/deploy/yourproject
git pull
source env/bin/activate
set -a; source /home/deploy/.env; set +a
python manage.py migrate
python manage.py collectstatic --noinput
sudo systemctl restart gunicorn

If requirements.txt changed, run pip install -r requirements.txt before migrate.

Step 7: Backups and monitoring

Database backup

A backup script that runs from cron can't type a password, so store the database password in ~/.pgpass. PostgreSQL reads it automatically, and ignores it unless only the owner can read it.

echo "localhost:5432:myproject:myprojectuser:secure_password_here" > /home/deploy/.pgpass
chmod 600 /home/deploy/.pgpass

Now the script:

#!/bin/bash
# /home/deploy/backup.sh
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/home/deploy/backups"
mkdir -p $BACKUP_DIR

pg_dump -h localhost -U myprojectuser myproject | gzip > "$BACKUP_DIR/db_$DATE.sql.gz"

# Keep last 7 days
find $BACKUP_DIR -name "db_*.sql.gz" -mtime +7 -delete

The -h localhost matters. Without it, pg_dump connects over the local socket using "peer" login, which only works when your Linux username matches the database username.

Make it executable and test it once by hand:

chmod +x /home/deploy/backup.sh
/home/deploy/backup.sh
ls -lh /home/deploy/backups

Then schedule it. crontab -e opens an editor; add this line at the bottom to run it every day at 3 AM:

0 3 * * * /home/deploy/backup.sh

A backup on the same server dies with the server. Copy the backups folder somewhere else on a schedule too.

Log monitoring

# Gunicorn errors
sudo journalctl -u gunicorn --since "1 hour ago"

# Nginx access
sudo tail -f /var/log/nginx/access.log | grep -E "50[0-9]|4[0-9]{2}"

# Django logs (if configured)
tail -f /home/deploy/yourproject/logs/django.log

Troubleshooting

502 Bad Gateway. Nginx can't reach Gunicorn. Run sudo systemctl status gunicorn.socket gunicorn and sudo journalctl -u gunicorn -n 50. Common causes: a typo in config.wsgi:application, a missing /var/log/gunicorn folder, or a missing environment variable (look for KeyError: 'DJANGO_SECRET_KEY').

400 Bad Request on every page. The domain isn't in ALLOWED_HOSTS. Add it and restart Gunicorn.

"This page isn't redirecting properly" / too many redirects. SECURE_SSL_REDIRECT = True without SECURE_PROXY_SSL_HEADER, or Nginx isn't sending X-Forwarded-Proto.

Site works but has no CSS (static files 404 or 403). A 404 means collectstatic hasn't run or the alias path is wrong. A 403 means Nginx can't enter /home/deploy. See the chmod 751 step. sudo tail /var/log/nginx/error.log shows the exact path it tried.

permission denied for schema public during migrate. The database isn't owned by your user. Run ALTER DATABASE myproject OWNER TO myprojectuser; in sudo -u postgres psql.

nginx -t fails with "cannot load certificate". The config references Let's Encrypt files before certbot created them. Use the HTTP-only config first, then run certbot.

certbot fails the challenge. Your domain's DNS doesn't point at this server yet, or port 80 is blocked. Check with dig +short example.com and sudo ufw status.

What I'd tell anyone doing this

  1. Never run runserver in production. Gunicorn under systemd is the minimum.

  2. Use a unix socket when Nginx and Gunicorn share a machine. There's no TCP port to conflict with or accidentally expose, and the socket's file permissions control who can talk to Gunicorn.

  3. Let Nginx serve static files. Run collectstatic, point Nginx's /static/ alias at the output, and add cache headers. Python has better things to do.

  4. Set DEBUG=False and test ALLOWED_HOSTS. The two classic deployment bugs are DEBUG=True in production (it shows stack traces and settings to anyone) and a missing ALLOWED_HOSTS entry (400 for every request).

  5. Keep secrets in environment variables. Never commit SECRET_KEY, database passwords or API keys. A .env file outside the repo, loaded by systemd's EnvironmentFile, is enough for one server.

  6. Run python manage.py check --deploy before going live. It catches missing security settings you'd otherwise find the hard way.

Next steps

  • Set up LOGGING in settings.py so Django writes errors to a file you can read later.
  • Copy backups off the server (rsync to another machine or object storage).
  • Add Redis as a cache once you have real traffic.

Get it


Last updated: 2026-09-01. Tested on Ubuntu 24.04 LTS with Django 6.0, Gunicorn 23.0, Nginx 1.24, PostgreSQL 16, Python 3.13.

Comments (0)

Join the discussion — sign in to comment.

Sign in

No comments yet — be the first to share your thoughts.