Deploy a Django App on a VPS with PostgreSQL and Gunicorn

In progress Django Linux

Goal

A Django app running on a fresh Ubuntu VPS (Hetzner or any provider), with PostgreSQL on the same machine and Gunicorn serving the app, ready to sit behind Nginx.

Prerequisites

  • A VPS running Ubuntu 24.04 and SSH access with a key (see Set Up SSH Key Authentication).
  • The project in a Git repository the server can clone.

Steps

  1. Update the system, rebooting if asked:
    sudo apt update && apt list --upgradable
    sudo apt upgrade
    
  2. Install the packages the stack needs:
    sudo apt install python3-pip python3-dev python3-venv libpq-dev \
      postgresql postgresql-contrib nginx certbot python3-certbot-nginx
    
  3. Create the database and its user, with the user as owner (required on PostgreSQL 15+, see PostgreSQL 15 Removed CREATE on the public Schema from Ordinary Users):
    sudo -u postgres psql
    
    CREATE ROLE appuser WITH LOGIN PASSWORD 'a-long-random-password';
    CREATE DATABASE appdb OWNER appuser;
    ALTER ROLE appuser SET client_encoding TO 'utf8';
    ALTER ROLE appuser SET default_transaction_isolation TO 'read committed';
    ALTER ROLE appuser SET timezone TO 'UTC';
    \q
    
  4. Give the server a deploy key for the repository (ssh-keygen -t ed25519, add the public key to GitHub/GitLab), check it with ssh -T git@gitlab.com, then clone into /apps/<app>.
  5. Create the environment and install dependencies, as a dedicated non-root user:
    cd /apps/<app>
    python3 -m venv .venv && source .venv/bin/activate
    pip install -r requirements.txt     # or: poetry install / uv sync
    
  6. Apply migrations and collect static files:
    python manage.py migrate
    python manage.py collectstatic --noinput
    
  7. Configure Gunicorn in config/gunicorn/prod.py:
    import multiprocessing
    wsgi_app = "core.wsgi:application"
    workers = multiprocessing.cpu_count() * 2 + 1
    bind = "127.0.0.1:8000"            # Nginx in front; never expose Gunicorn directly
    accesslog = "-"
    errorlog = "-"
    
  8. Run Gunicorn as a systemd service (ExecStart=/apps/<app>/.venv/bin/gunicorn -c config/gunicorn/prod.py, User= the app user, Restart=on-failure), then sudo systemctl enable --now <app>.
  9. Point Nginx at 127.0.0.1:8000, serve /static/ from STATIC_ROOT, and get a certificate with sudo certbot --nginx.

Verify

  • systemctl status <app> shows active (running).
  • curl -I http://127.0.0.1:8000 answers on the server; the domain answers over HTTPS through Nginx.
  • ss -tlnp shows Gunicorn on 127.0.0.1 only.

Troubleshooting

  • permission denied for schema public during migrate: the app user doesn't own the database; ALTER DATABASE appdb OWNER TO appuser;.
  • DisallowedHost: add the domain to ALLOWED_HOSTS.
  • Static files 404 behind Nginx: check STATIC_ROOT, that collectstatic ran, and the Nginx alias path.

References