All posts

Blog

How to Deploy a Django App on a VPS with Gunicorn and Nginx

Illustrated cover for the Developers guide "How to Deploy a Django App on a VPS with Gunicorn and Nginx"

Django's runserver command is wonderful for development and explicitly not meant for production. The Django documentation says as much. When it is time to put your project on the internet, the well-trodden path is Gunicorn as the WSGI application server, Nginx as the reverse proxy and static file server, and systemd to keep everything running.

This guide walks through how to deploy a Django app on a VPS running Ubuntu. The same approach works for Flask and other WSGI frameworks with small changes.

What each piece does

  • Gunicorn runs your Python code and speaks WSGI to Django.
  • Nginx accepts public HTTP/HTTPS connections, serves /static/ and /media/ files directly (it is much faster at that than Python), and forwards everything else to Gunicorn.
  • systemd starts Gunicorn at boot and restarts it if it crashes.
  • PostgreSQL (recommended) stores your data. SQLite works for tiny projects, but PostgreSQL is the usual production choice for Django.

Step 1: Install system packages

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

libpq-dev and build-essential are needed if pip has to compile the PostgreSQL driver.

Step 2: Create the database

sudo -u postgres psql
CREATE DATABASE myproject;
CREATE USER myproject_user WITH PASSWORD 'a-long-random-password';
ALTER ROLE myproject_user SET client_encoding TO 'utf8';
ALTER ROLE myproject_user SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE myproject TO myproject_user;
\c myproject
GRANT ALL ON SCHEMA public TO myproject_user;
\q

The schema grant matters on PostgreSQL 15 and newer, where ordinary users no longer get create rights on the public schema by default.

Step 3: Get the code and create a virtual environment

sudo mkdir -p /srv/myproject
sudo chown $USER:$USER /srv/myproject
cd /srv/myproject
git clone https://github.com/yourname/myproject.git .
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
pip install gunicorn psycopg

Using a virtual environment keeps your project's packages separate from the system Python, which Ubuntu relies on. Do not install project packages globally with sudo pip.

Step 4: Production settings

Before anything faces the internet, update your settings. Load secrets from environment variables rather than committing them:

import os

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": "myproject",
        "USER": "myproject_user",
        "PASSWORD": os.environ["DB_PASSWORD"],
        "HOST": "localhost",
    }
}

STATIC_URL = "/static/"
STATIC_ROOT = "/srv/myproject/staticfiles"
MEDIA_URL = "/media/"
MEDIA_ROOT = "/srv/myproject/media"

SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

Put the environment variables in a file such as /srv/myproject/.env with tight permissions (chmod 600), and have systemd load it (shown below).

Django ships a useful checker:

python manage.py check --deploy

It flags common production misconfigurations. Work through its warnings.

Then run migrations and collect static files:

python manage.py migrate
python manage.py collectstatic --noinput
python manage.py createsuperuser

Step 5: Test Gunicorn

From the project directory, with the virtual environment active (replace myproject with the package containing wsgi.py):

gunicorn --bind 127.0.0.1:8000 myproject.wsgi

If it starts without errors, stop it with Ctrl+C. Gunicorn's documentation suggests starting with roughly (2 x CPU cores) + 1 workers and adjusting from there based on memory and load.

Step 6: Run Gunicorn with systemd

Create a service file:

sudo nano /etc/systemd/system/myproject.service
[Unit]
Description=Gunicorn for myproject
After=network.target

[Service]
User=deploy
Group=www-data
WorkingDirectory=/srv/myproject
EnvironmentFile=/srv/myproject/.env
ExecStart=/srv/myproject/venv/bin/gunicorn \
    --workers 3 \
    --bind unix:/run/myproject/gunicorn.sock \
    myproject.wsgi:application
RuntimeDirectory=myproject
Restart=on-failure

[Install]
WantedBy=multi-user.target

Replace deploy with your username. RuntimeDirectory makes systemd create /run/myproject for the socket each time the service starts. Using a Unix socket instead of a TCP port avoids exposing Gunicorn on the network at all.

sudo systemctl daemon-reload
sudo systemctl enable --now myproject
sudo systemctl status myproject

If something fails, journalctl -u myproject -e shows the error.

Step 7: Configure Nginx

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

    location /static/ {
        alias /srv/myproject/staticfiles/;
    }

    location /media/ {
        alias /srv/myproject/media/;
    }

    location / {
        proxy_pass http://unix:/run/myproject/gunicorn.sock;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Enable and reload:

sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

Nginx needs permission to read the static files and connect to the socket. Because the service runs with group www-data, Nginx (which runs as www-data on Ubuntu) can reach the socket; make sure parent directories are traversable too.

Step 8: HTTPS with Certbot

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com

Once HTTPS works, consider enabling SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE, and CSRF_COOKIE_SECURE in Django.

Deploying updates

cd /srv/myproject
git pull
source venv/bin/activate
pip install -r requirements.txt
python manage.py migrate
python manage.py collectstatic --noinput
sudo systemctl restart myproject

Script it, and you have a one-command deploy.

Common problems and fixes

  • 502 Bad Gateway: Gunicorn is not running or the socket path in Nginx does not match the one in the service file. Check systemctl status myproject and confirm the socket exists in /run/myproject/.
  • Static files return 404: you forgot collectstatic, or the alias path is missing its trailing slash.
  • "Bad Request (400)": the domain you are visiting is not in ALLOWED_HOSTS.
  • CSRF failures on forms after enabling HTTPS: add your HTTPS origins to CSRF_TRUSTED_ORIGINS and make sure Nginx sends X-Forwarded-Proto.

Wrap-up

To deploy a Django app on a VPS reliably, keep the roles separate: Gunicorn runs Python, Nginx serves static files and handles HTTPS, systemd keeps the process alive, and PostgreSQL holds the data. Turn off DEBUG, keep secrets in environment variables, run check --deploy, and back up your database regularly. That setup will carry a Django project a long way.