On this page
- What do you need before deploying Django?
- How do you create the database and its owner?
- Where should the code and virtual environment live?
- Which settings must change for production?
- How do you migrate, collect static files and check the configuration?
- How do you run Gunicorn as a systemd service?
- How do you configure Nginx in front of Gunicorn?
- How do you open the firewall and add HTTPS?
- How do you ship updates and fix common errors?
- Questions
What do you need before deploying Django?
You need a server with a sudo user, a domain pointing at it, and a Python new enough for your Django release. Django 5.2 LTS runs on Python 3.10 and later, while Django 6.0 needs Python 3.12 or later. That means Ubuntu 24.04 and Debian 13 can use either, Ubuntu 22.04 and Debian 12 are fine for 5.2, and Rocky or Alma should use the python3.12 package instead of the default 3.9. The Python, pip and venv guide explains the interpreter choices in more detail, and DNS records covers the A and AAAA entries for app.example.net.
Install the system packages in one go:
# Ubuntu and Debian
sudo apt update
sudo apt install -y python3-venv python3-dev build-essential postgresql nginx
# Rocky Linux 9 and AlmaLinux 9
sudo dnf module list postgresql
sudo dnf module enable -y postgresql:16
sudo dnf install -y python3.12 python3.12-devel gcc postgresql-server nginx policycoreutils-python-utils
sudo postgresql-setup --initdb
sudo systemctl enable --now postgresql nginxOn the apt systems PostgreSQL and Nginx start automatically. Confirm with systemctl status postgresql nginx and psql --version.
How do you create the database and its owner?
Create one login role and one database owned by it, so the application never connects as the superuser.
sudo -u postgres psql
CREATE ROLE mysite WITH LOGIN PASSWORD 'use-a-long-random-password';
CREATE DATABASE mysite OWNER mysite;
\qUbuntu and Debian already accept password logins over 127.0.0.1. Rocky and Alma ship ident for TCP connections, so open /var/lib/pgsql/data/pg_hba.conf, change the method on the 127.0.0.1/32 and ::1/128 host lines to scram-sha-256, and run sudo systemctl restart postgresql. Then prove the credentials work:
psql -h 127.0.0.1 -U mysite -d mysite -c "select version();"PostgreSQL listens only on localhost by default. Keep it that way unless another machine must reach it.
Where should the code and virtual environment live?
A directory under /srv owned by your deploy user keeps the project away from home directory permissions and makes the SELinux labels on Rocky and Alma straightforward.
sudo mkdir -p /srv/mysite
sudo chown deploy:deploy /srv/mysite
cd /srv/mysite
git clone https://git.example.net/you/mysite.git . # or copy your project here
python3 -m venv .venv # Rocky and Alma: python3.12 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
pip install gunicorn "psycopg[binary]"
python -m django --versionIf you are only testing, pip install "django>=5.2" gunicorn "psycopg[binary]" followed by django-admin startproject mysite . gives you a working project in the same layout. Record the exact versions with pip freeze > requirements.txt so later deploys are repeatable.
Which settings must change for production?
Turn DEBUG off, list your hostnames, load the secret key and database password from the environment, and define where static files are collected. Keep the values in a root owned file that only the service group can read:
sudo install -m 640 -o root -g deploy /dev/null /etc/mysite.env
sudo nano /etc/mysite.envDJANGO_SECRET_KEY=paste-output-of-the-command-below
DJANGO_ALLOWED_HOSTS=app.example.net
DB_NAME=mysite
DB_USER=mysite
DB_PASSWORD=use-a-long-random-password
DB_HOST=127.0.0.1Generate a key with python -c "import secrets; print(secrets.token_urlsafe(50))". Then adjust mysite/settings.py:
import os
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = os.environ.get("DJANGO_DEBUG", "0") == "1"
ALLOWED_HOSTS = os.environ["DJANGO_ALLOWED_HOSTS"].split(",")
CSRF_TRUSTED_ORIGINS = ["https://app.example.net"]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": os.environ["DB_NAME"],
"USER": os.environ["DB_USER"],
"PASSWORD": os.environ["DB_PASSWORD"],
"HOST": os.environ.get("DB_HOST", "127.0.0.1"),
"PORT": "5432",
"CONN_MAX_AGE": 60,
}
}
STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
MEDIA_URL = "media/"
MEDIA_ROOT = BASE_DIR / "media"
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = TrueThe proxy header line tells Django that a request arriving from Nginx over HTTPS really was secure. Because the cookies are marked secure, log in to the admin only after the certificate is in place.
How do you migrate, collect static files and check the configuration?
Load the environment file into your shell, then run the usual management commands from the project directory.
cd /srv/mysite
source .venv/bin/activate
set -a; source /etc/mysite.env; set +a
python manage.py migrate
python manage.py collectstatic --noinput
python manage.py createsuperuser
python manage.py check --deploycollectstatic copies every app asset, including the admin styles, into staticfiles/. The deploy check lists remaining warnings such as HSTS; read each one and decide, rather than silencing them all. A quick smoke test before systemd is involved: gunicorn mysite.wsgi:application --bind 127.0.0.1:8000, then from a second session curl -I -H "Host: app.example.net" http://127.0.0.1:8000/.
How do you run Gunicorn as a systemd service?
A small unit file starts Gunicorn at boot, restarts it on failure and feeds it the environment file. Create /etc/systemd/system/mysite.service:
[Unit]
Description=Gunicorn for mysite
After=network.target postgresql.service
[Service]
User=deploy
Group=deploy
WorkingDirectory=/srv/mysite
EnvironmentFile=/etc/mysite.env
ExecStart=/srv/mysite/.venv/bin/gunicorn mysite.wsgi:application --bind 127.0.0.1:8000 --workers 3 --timeout 60 --access-logfile -
Restart=on-failure
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload
sudo systemctl enable --now mysite
systemctl status mysite
ss -ltnp | grep 8000A common starting point for workers is two per vCPU plus one, but memory matters more on small plans: each worker loads the whole project, so on 1 GB keep it at two or three and watch free -h. The systemd services guide covers unit options further.
How do you configure Nginx in front of Gunicorn?
Nginx answers on ports 80 and 443, serves collected static files itself and forwards everything else to Gunicorn with the original host and scheme. On Ubuntu and Debian write /etc/nginx/sites-available/mysite and link it into sites-enabled; on Rocky and Alma write /etc/nginx/conf.d/mysite.conf.
server {
listen 80;
listen [::]:80;
server_name app.example.net;
client_max_body_size 20m;
location /static/ {
alias /srv/mysite/staticfiles/;
}
location /media/ {
alias /srv/mysite/media/;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}# Ubuntu and Debian
sudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
# Rocky and Alma: allow the proxy and label the asset folders
sudo setsebool -P httpd_can_network_connect 1
sudo semanage fcontext -a -t httpd_sys_content_t "/srv/mysite/(staticfiles|media)(/.*)?"
sudo restorecon -Rv /srv/mysite
sudo nginx -t && sudo systemctl reload nginxNginx also needs to traverse /srv/mysite; the default 755 mode on that directory is enough.
How do you open the firewall and add HTTPS?
Allow web traffic in the server firewall, then let Certbot fetch a certificate and rewrite the Nginx block for you.
# Ubuntu and Debian
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo apt install -y certbot python3-certbot-nginx
# Rocky and Alma
sudo firewall-cmd --permanent --add-service=http --add-service=https
sudo firewall-cmd --reload
sudo dnf install -y epel-release
sudo dnf install -y certbot python3-certbot-nginx
sudo certbot --nginx -d app.example.net --redirect
curl -I https://app.example.net/admin/login/Certbot installs a timer that renews certificates automatically; sudo certbot renew --dry-run proves renewal works. Our firewall rules tutorial and the Certbot guide go deeper.
How do you ship updates and fix common errors?
An update is a pull, an install, a migration, a static rebuild and a restart:
cd /srv/mysite && source .venv/bin/activate
set -a; source /etc/mysite.env; set +a
git pull
pip install -r requirements.txt
python manage.py migrate
python manage.py collectstatic --noinput
sudo systemctl restart mysite- 400 Bad Request: the hostname is missing from
DJANGO_ALLOWED_HOSTS. - 502 Bad Gateway: Gunicorn is not running or crashed on import; read
journalctl -u mysite -n 50. - Pages without styles:
collectstaticwas not run, thealiaspath is wrong, or SELinux labels are missing. - CSRF verification failed: add the full https origin to
CSRF_TRUSTED_ORIGINS.
Nightly pg_dump output plus the optional daily backups add-on keep both data and code recoverable.
Plans that fit this guide
Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.
| Plan | Fits because | Size | Monthly | Order from |
|---|---|---|---|---|
| A1-2 | small site with PostgreSQL on the same server | 1 vCPU, 2 GB RAM, 50 GB NVMe | $7.20/mo | $43.20 for 6 months |
| A2-4 | more Gunicorn workers and room for Celery | 2 vCPU, 4 GB RAM, 100 GB NVMe | $14.40/mo | $43.20 for 3 months |
| F4-16 | busy site with a larger database cache | 4 vCPU, 16 GB RAM, 384 GB NVMe | $57.60/mo | $57.60 for 1 month |
Questions about Deploy Django with Gunicorn and Nginx
Should I use Gunicorn or uWSGI for Django?
Gunicorn is simple to configure and works well for most Django sites. uWSGI has more knobs but more to learn. If your project uses async views heavily, run Gunicorn with Uvicorn workers or switch to an ASGI server.
Can I keep using SQLite in production?
For a small site with few writes, SQLite works. PostgreSQL handles concurrent writes, has better tooling for backups and is what most Django add-ons are tested against, so it is the safer default on a server.
Why does the admin look unstyled after deploy?
Static files are not served by Django when DEBUG is off. Run collectstatic and make sure the Nginx location /static/ alias points at STATIC_ROOT with a trailing slash.
How many Gunicorn workers fit on a 1 GB server?
Usually two or three for a typical project. Check memory after a few requests with free -h and systemctl status mysite, and add a swap file as a safety net.
Where should media uploads go?
Keep them outside the code checkout or in a separate directory such as /srv/mysite/media owned by the deploy user, so a fresh clone never deletes them, and include that folder in your backups.
How do I grow when traffic increases?
There is no in-place resize, so deploy a larger plan, copy the database dump and project, switch DNS, and destroy the old server. The move to a larger plan tutorial walks through it.
More in Python
- Install Python 3, pip and venv
- Run legacy Python 2 code
- Manage Python projects with Poetry
- Miniconda and Anaconda on a server
- Deploy Flask with Gunicorn and Nginx
- Deploy FastAPI with Uvicorn workers
- Background tasks with Celery and Redis
- Host a Python Discord bot
- Containerise a Python web app
- JupyterLab on a server
- Host a Python Telegram bot