Django · DevOps · Nginx

Deploying Django to Production on Ubuntu with Gunicorn, Nginx and systemd

Sifat Ali Published 2 min read

There are many ways to run Django in production. This is the one I recommend for most teams starting out: a single Ubuntu server, Gunicorn managed by systemd, Nginx in front, and HTTPS from Let’s Encrypt. It is conventional, well documented and easy to reason about at 3 a.m.

The examples use a project called config (the folder containing wsgi.py), deployed to /srv/myapp, served at example.com. Adjust the names to match your project.

1. Prepare the server

sudo apt update && sudo apt upgrade -y
sudo apt install -y python3-venv python3-dev build-essential libpq-dev nginx

# a dedicated, unprivileged user for the application
sudo adduser --system --group --home /srv/myapp myapp

Lock down SSH (key-based login only) and enable the firewall before going further:

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

2. Install the application

sudo -u myapp -H bash
cd /srv/myapp
git clone https://github.com/you/myapp.git app
python3 -m venv venv
venv/bin/pip install --upgrade pip
venv/bin/pip install -r app/requirements.txt gunicorn

Keep secrets out of the repository. Put them in an environment file that only the app user can read:

# /srv/myapp/.env  (chmod 600, owned by myapp)
DJANGO_SETTINGS_MODULE=config.settings
DJANGO_SECRET_KEY=change-me
DATABASE_URL=postgres://myapp:password@localhost:5432/myapp
ALLOWED_HOSTS=example.com,www.example.com

3. Production settings for a proxied app

Django sits behind Nginx, so it must be told which requests were originally HTTPS:

# settings.py (production)
DEBUG = False
ALLOWED_HOSTS = os.environ["ALLOWED_HOSTS"].split(",")
CSRF_TRUSTED_ORIGINS = ["https://example.com", "https://www.example.com"]

SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000  # enable once HTTPS works everywhere

STATIC_ROOT = "/srv/myapp/static"

SECURE_PROXY_SSL_HEADER is only safe because Nginx always sets X-Forwarded-Proto itself, overwriting anything a client sends. Then prepare the release:

set -a; source /srv/myapp/.env; set +a
cd /srv/myapp/app
../venv/bin/python manage.py check --deploy
../venv/bin/python manage.py migrate
../venv/bin/python manage.py collectstatic --noinput

4. Run Gunicorn with systemd socket activation

With socket activation, systemd owns the listening socket and hands it to Gunicorn. The socket stays open even while Gunicorn restarts, so requests queue instead of failing.

# /etc/systemd/system/gunicorn.socket
[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock
SocketUser=www-data

[Install]
WantedBy=sockets.target
# /etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon for myapp
Requires=gunicorn.socket
After=network.target

[Service]
Type=notify
User=myapp
Group=myapp
WorkingDirectory=/srv/myapp/app
EnvironmentFile=/srv/myapp/.env
ExecStart=/srv/myapp/venv/bin/gunicorn --workers 3 --access-logfile - config.wsgi:application
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now gunicorn.socket
curl --unix-socket /run/gunicorn.sock http://localhost/  # starts gunicorn on demand
sudo journalctl -u gunicorn -f                           # logs

5. Configure Nginx

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

    client_max_body_size 10m;

    location /static/ {
        alias /srv/myapp/static/;
        expires 30d;
        access_log off;
    }

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

6. Add HTTPS with Let’s Encrypt

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
sudo certbot renew --dry-run   # confirms automatic renewal works

Certbot edits the server block to listen on 443 and redirect HTTP to HTTPS. Once everything loads over HTTPS, it is safe to keep SECURE_HSTS_SECONDS enabled.

7. Background workers with Celery

Celery workers are separate long-running processes, so they get their own unit:

# /etc/systemd/system/celery.service
[Unit]
Description=celery worker for myapp
After=network.target redis-server.service

[Service]
User=myapp
Group=myapp
WorkingDirectory=/srv/myapp/app
EnvironmentFile=/srv/myapp/.env
ExecStart=/srv/myapp/venv/bin/celery -A config worker --loglevel=INFO --concurrency=2
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

If you use scheduled tasks, run celery -A config beat as one more unit, and only one instance of it.

8. Deploy updates

A deploy script makes releases repeatable:

#!/usr/bin/env bash
set -euo pipefail
set -a; source /srv/myapp/.env; set +a
cd /srv/myapp/app
git pull --ff-only
../venv/bin/pip install -r requirements.txt
../venv/bin/python manage.py migrate --noinput
../venv/bin/python manage.py collectstatic --noinput
sudo systemctl reload gunicorn   # graceful: new workers, no dropped requests
sudo systemctl restart celery

Final checklist

  • DEBUG = False and manage.py check --deploy passes
  • Secrets live in an environment file readable only by the app user
  • Gunicorn runs under systemd with socket activation
  • Nginx serves static files and proxies everything else
  • HTTPS with automatic renewal and HTTP redirected to HTTPS
  • Firewall allows only SSH and web traffic
  • Celery workers and beat run as supervised services
  • Deploys use one script, not memory

This setup comfortably runs a lot of production traffic, and every piece of it is standard Linux you can debug with standard tools. If you would rather have someone set it up and document it for your team, see my deployment and DevOps service.

Sifat Ali

Written by

Full Stack Software Engineer. I engineer scalable backend systems, intelligent AI-powered applications, and production-ready digital products that solve real-world problems.

Frequently asked questions

Why use Nginx in front of Gunicorn?

Gunicorn is designed to run behind a proxy. Nginx buffers slow clients so Gunicorn workers are not tied up, serves static files efficiently, terminates TLS, and lets you add compression, caching and security headers.

How many Gunicorn workers should I run?

A common starting point is (2 x CPU cores) + 1 for synchronous workers, then adjust based on memory use and real traffic. I/O-heavy apps may do better with threads or an async worker class.

How do I reload Django code without downtime?

Send Gunicorn a HUP signal (systemctl reload with ExecReload configured). Gunicorn starts new workers with the new code and gracefully stops the old ones. With systemd socket activation, the listening socket stays open even during a full restart.

What does manage.py check --deploy do?

It runs Django's deployment checklist against your settings and warns about insecure or missing production settings such as DEBUG, SECRET_KEY strength, HSTS, secure cookies and SSL redirects.