How to Deploy a Django App on a VPS: Ubuntu, PostgreSQL, Gunicorn, Nginx and HTTPS

To deploy a Django app on a VPS, install the project on an Ubuntu server, run it with Gunicorn under systemd, put Nginx in front as a reverse proxy and add a free Let’s Encrypt certificate with Certbot. The setup takes six stages, and every command below is written for Ubuntu 24.04 LTS and Django 6.1.

The stack has five parts: an Ubuntu 24.04 VPS with root SSH access, PostgreSQL 16 for data, Gunicorn as the WSGI server, Nginx for static files and request proxying, and Certbot for HTTPS. Each section covers one part and works without the others, so you can open the stage you need directly.

Choose a VPS for a Django App

A production Django app with PostgreSQL on one server needs a KVM VPS with root access, an Ubuntu LTS image and enough memory for the database plus Gunicorn workers.

Step 1. Size the plan by RAM and vCPU

Start with 2 GB RAM and 2 vCPU for a small production site: PostgreSQL and five Gunicorn workers fit with headroom for the operating system. Take 1 GB for staging copies and pet projects, and 4 GB or more when the app also runs Celery workers or Redis.

Step 2. Pick the data center location

Choose the location closest to most of your users, because network latency is added to every request. LikeVPS runs servers in 25 countries, including Germany, the Netherlands and the USA.

Step 3. Select Ubuntu 24.04 LTS as the operating system

Select Ubuntu 24.04 LTS when you order the server. Its repositories ship Python 3.12 and PostgreSQL 16, which meet Django 6.1’s Python version requirements and its PostgreSQL 15 minimum; Ubuntu 22.04 ships PostgreSQL 14, which Django 6.1 no longer supports.

Step 4. Point the domain to the server

Open the DNS settings of your domain and create A records for example.com and www.example.com with the server’s IPv4 address. Certbot validates the domain through these records, so add them before the HTTPS stage.

Order a LikeVPS VPS/VDS server with NVMe SSD, ECC memory and built-in DDoS protection: the server is provisioned automatically after payment, and the login details arrive by email.

LikeVPS VPS/VDS server page with plan cards and country flags

Prepare the Ubuntu VPS for Django

A fresh Ubuntu 24.04 VPS needs updated packages, Python tooling, a non-root user and a firewall before any Django code goes on it.

Step 1. Connect to the server over SSH

Open a terminal on your computer and connect as root with the IP address from the server’s welcome email. Type yes when SSH asks whether to trust the host key; the Ubuntu shell prompt appears.

ssh root@203.0.113.10

Terminal with the Ubuntu 24.04 login banner after the first SSH connection

Step 2. Update the system and install Python tools

Upgrade the installed packages, then add the virtual environment module, Git and the UFW firewall. Ubuntu 24.04 refuses system-wide pip install, so python3-venv is required for the project environment.

apt update && apt upgrade -y
apt install -y python3-venv python3-pip git ufw

Step 3. Create a deploy user with sudo rights

Create a separate Linux user for the application and add it to the sudo group. Set a password at the prompt; the remaining fields can stay empty.

adduser deploy
usermod -aG sudo deploy

Step 4. Copy your SSH key to the new user

On your own computer, run ssh-copy-id to install your public key for deploy, then log in as that user for the rest of the setup.

ssh-copy-id deploy@203.0.113.10
ssh deploy@203.0.113.10

Step 5. Enable the UFW firewall

Allow SSH before you enable the firewall, otherwise the current session can be cut off. Confirm with y; ufw status then lists OpenSSH as ALLOW.

sudo ufw allow OpenSSH
sudo ufw enable
sudo ufw status

ufw status output with OpenSSH set to ALLOW

Set Up PostgreSQL for a Django Project

Django recommends PostgreSQL for production, and Django 6.1 requires PostgreSQL 15 or newer, so the PostgreSQL 16 package from the Ubuntu 24.04 repositories works without extra sources.

Step 1. Install PostgreSQL

Install the server package on the VPS; Ubuntu starts the PostgreSQL service right after installation.

sudo apt install -y postgresql

Step 2. Open the psql shell

Start psql as the postgres system user. The prompt changes to postgres=#.

sudo -u postgres psql

psql prompt postgres=# in the terminal

Step 3. Create the database and its owner

Create a role for the app and a database owned by that role, then save the connection defaults Django expects so it skips extra setup queries on each connection. Database ownership lets the role create tables in the public schema, a right that ordinary roles no longer get by default since PostgreSQL 15.

CREATE USER myproject WITH PASSWORD 'strong-password';
CREATE DATABASE myproject OWNER myproject;
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';
\q

Upload the Django Project and Set Production Settings

On the VPS, the Django project lives in /srv/myproject with its own Python virtual environment, and secrets come from an environment file instead of settings.py.

Step 1. Clone the repository

Create the project folder, hand it to the deploy user and clone your repository into it. Replace the URL with your own; a private repository needs a deploy key or access token on the server first.

sudo mkdir -p /srv/myproject
sudo chown deploy:deploy /srv/myproject
git clone https://github.com/you/myproject.git /srv/myproject

Step 2. Create the virtual environment

Create the environment inside the project folder and install the project requirements together with Gunicorn and psycopg 3, the PostgreSQL driver Django recommends.

cd /srv/myproject
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt gunicorn "psycopg[binary]"

Step 3. Store secrets in an environment file

Generate a secret key, create .env in the project folder with the three variables below and close the file to other users. Both systemd and your shell read this file, so keep one KEY=value pair per line.

python3 -c "import secrets; print(secrets.token_urlsafe(50))"
nano .env
chmod 600 .env
# /srv/myproject/.env
DJANGO_SECRET_KEY=paste-the-generated-key
DJANGO_ALLOWED_HOSTS=example.com,www.example.com
DB_PASSWORD=strong-password

.env file open in the nano editor with the three variables

Step 4. Edit settings.py for production

Open myproject/settings.py and replace the matching lines with the block below. The Django deployment checklist is explicit: “You must never enable debug in production.” SECURE_PROXY_SSL_HEADER lets Django recognize requests that Nginx received over HTTPS, and the two cookie flags block admin login over plain HTTP until the certificate is installed.

import os

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = False
ALLOWED_HOSTS = os.environ["DJANGO_ALLOWED_HOSTS"].split(",")

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": "myproject",
        "USER": "myproject",
        "PASSWORD": os.environ["DB_PASSWORD"],
        "HOST": "127.0.0.1",
        "PORT": "5432",
    }
}

STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"

SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True

Step 5. Migrate, collect static files and run the deploy check

Load the variables into the shell, apply migrations, copy static files to STATIC_ROOT and create an admin account. check --deploy then lists the production settings that still need attention; the HSTS and SSL redirect warnings can wait until HTTPS works. In projects created with Django 6.1, the check also reports mail.E001 until the MAILERS setting points to a production email backend such as SMTP.

set -a; source .env; set +a
python manage.py migrate
python manage.py collectstatic --noinput
python manage.py createsuperuser
python manage.py check --deploy

Output of manage.py check --deploy in the terminal

Run Django with Gunicorn and systemd

Gunicorn is the WSGI server that executes Django code, and systemd keeps it running, restarts it after failures and starts it at boot. The unit files assume the project in /srv/myproject, the virtual environment in /srv/myproject/venv and the Linux user deploy.

Step 1. Create the socket unit

Open a new unit file and paste the socket definition from the Gunicorn deployment documentation. The socket belongs to www-data, the user Nginx runs as on Ubuntu, so Nginx can connect to it.

sudo nano /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

gunicorn.socket open in the nano editor

Step 2. Create the service unit

Create gunicorn.service with the content below. Set --workers with Gunicorn’s starting formula (2 × CPU cores) + 1: 3 workers for 1 vCPU, 5 for 2 vCPU.

sudo nano /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
EnvironmentFile=/srv/myproject/.env
ExecStart=/srv/myproject/venv/bin/gunicorn --workers 3 myproject.wsgi
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Step 3. Start the socket and test Gunicorn

Enable the socket so it listens now and after every reboot, then send a test request through it as www-data. The first request starts gunicorn.service, the response is your site’s HTML, and systemctl status shows active (running).

sudo systemctl enable --now gunicorn.socket
sudo -u www-data curl -H "Host: example.com" --unix-socket /run/gunicorn.sock http://localhost/
sudo systemctl status gunicorn

systemctl status gunicorn showing active (running)

Configure Nginx as a Reverse Proxy for Django

Nginx receives browser requests, serves Django’s collected static files straight from disk and passes every other request to the Gunicorn socket at /run/gunicorn.sock.

Step 1. Install Nginx and open web ports

Install the package and allow the Nginx Full firewall profile, which opens ports 80 and 443.

sudo apt install -y nginx
sudo ufw allow 'Nginx Full'

Step 2. Create the server block

Create a site file for the project with the configuration below. The first server block drops requests for unknown host names with code 444, as the Django deployment checklist recommends; the second serves /static/ from STATIC_ROOT and proxies the rest with the headers from the Gunicorn documentation.

sudo nano /etc/nginx/sites-available/myproject
server {
    listen 80 default_server;
    return 444;
}

server {
    listen 80;
    server_name example.com www.example.com;

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

    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://unix:/run/gunicorn.sock;
    }
}

Nginx server block for the Django project open in the nano editor

Step 3. Enable the site and reload Nginx

Link the site into sites-enabled, remove the default site, which also claims default_server, and test the syntax. Reload only after nginx -t reports syntax is ok and test is successful.

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 output with “syntax is ok” and “test is successful”

Step 4. Open the site in a browser

Go to http://example.com in your browser: the Django home page loads with its stylesheets and images.

Django home page at http://example.com with styles loaded

Enable HTTPS for Django with Let’s Encrypt and Certbot

Certbot obtains a free Let’s Encrypt certificate for the Django site, adds it to the Nginx server block and renews it automatically. It needs a working HTTP site on port 80 and DNS A records that point to the VPS.

Step 1. Install Certbot from snap

Install Certbot as a snap, as the official Certbot instructions for Nginx recommend, and link the command into your path. If the snap command is missing, install snapd with sudo apt install -y snapd first.

sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/local/bin/certbot

Step 2. Request the certificate for both host names

Run Certbot with the Nginx plugin, list both domains and answer the prompts in the terminal. The --redirect option from the Certbot user guide adds a permanent HTTP-to-HTTPS redirect to the server block, so Django receives only HTTPS traffic.

sudo certbot --nginx --redirect -d example.com -d www.example.com

Certbot success message in the terminal

Step 3. Test automatic renewal

Run a dry-run renewal to confirm that renewal will work. The Certbot package installs a cron job or systemd timer that renews certificates before they expire.

sudo certbot renew --dry-run

Step 4. Check HTTPS and the admin login

Open https://example.com/admin/ in the browser: the lock icon appears in the address bar, and the login form works because CSRF and session cookies now travel over HTTPS.

Django admin login page over HTTPS with the lock icon in the address bar

Update a Deployed Django App

Every new release of a Django app on the VPS repeats one sequence: pull the code, install dependencies, migrate, collect static files and reload Gunicorn without dropping connections.

Step 1. Run the release commands

Connect as deploy and run the block below. Save it as deploy.sh in the project folder to ship each release with one command.

cd /srv/myproject
git pull
source venv/bin/activate
set -a; source .env; set +a
pip install -r requirements.txt
python manage.py migrate
python manage.py collectstatic --noinput
sudo systemctl reload gunicorn

Step 2. Confirm the workers restarted

systemctl reload sends HUP to the Gunicorn master, which restarts the workers with the new code while the systemd socket keeps accepting requests. Read the last log lines to confirm the workers booted without errors.

sudo journalctl -u gunicorn -n 20

journalctl output with Gunicorn “Booting worker” lines

When traffic outgrows the plan, upgrade it in the LikeVPS billing portal: the upgrade needs no reinstallation, so the Django app, database and settings stay in place. For CPU-bound views and background jobs, choose High Performance VPS plans on AMD Ryzen 9 7950X cores at up to 5.7 GHz.

FAQ: Deploying Django on a VPS

Do I need Docker to deploy Django on a VPS?

No. Gunicorn, Nginx and systemd run Django directly on Ubuntu; Docker pays off when several services or environments must use identical images.

Can I use Django’s runserver in production?

No. Django’s documentation states that runserver is not designed for a production setting, so a WSGI or ASGI server has to handle live traffic.

Why does the site return Bad Request (400) after deployment?

The requested domain is missing from the ALLOWED_HOSTS setting. With DEBUG = False, Django answers every unlisted host with Bad Request (400), so include both the bare domain and the www version.

What causes 502 Bad Gateway from Nginx?

Nginx cannot reach Gunicorn: the service failed to start, or the socket path in proxy_pass differs from ListenStream in gunicorn.socket. The Python traceback behind a failed start is in the systemd journal of the gunicorn unit.

Should I use Gunicorn or Uvicorn for Django?

Use Gunicorn for a standard WSGI Django project. Switch to an ASGI server such as Uvicorn when the app relies on async views, WebSockets or Django Channels.

How do I back up the Django database on a VPS?

Dump it with pg_dump on a schedule, for example sudo -u postgres pg_dump -Fc myproject > /var/backups/myproject.dump in a daily root cron job, and copy the file off the server.

Can Django and PostgreSQL share one VPS?

Yes, a VPS with 2–4 GB RAM runs both for most small and medium projects. Move PostgreSQL to a separate machine, such as a dedicated server, when database queries start competing with Gunicorn workers for CPU and memory.

How much does it cost to host a Django app on a VPS?

A 2 GB RAM VPS that runs Django, PostgreSQL and Nginx together costs from $12 per month at LikeVPS on monthly billing, and the Let’s Encrypt certificate is free.

Compare current VPS prices by country and billing term, then order the plan that fits your Django project.