ZetCode

Django deployment

last modified November 22, 2026 Python 3.15

The development server of Django is meant for one developer on one machine. In production, a request passes through several programs. A web server such as Nginx accepts the connections from the internet, handles HTTPS, and passes the requests to an application server such as Gunicorn. Gunicorn runs several worker processes with our Django code, and a service manager such as systemd starts Gunicorn at boot and restarts it when it fails. Static files, the stylesheets and scripts, are collected into one directory and served with long cache headers. In this article we take a small project through all these steps: first on the development machine, then on a Debian 12 server with systemd and Nginx 1.22. The examples use Django 6.1, Gunicorn 27, WhiteNoise 6.12, and Python 3.15.

The settings that matter for production, such as DEBUG, ALLOWED_HOSTS, and the secret key, are explained in more detail in Django settings and environment, and static files in Django static files. Here we use them on a real server.

The example project

The project is created with uv; the steps are explained in Django introduction. The commands below create a project directory, install Django, the application server Gunicorn, and WhiteNoise, which serves static files, generate the project with the configuration package config, and start the app quotes.

$ mkdir quotesite
$ cd quotesite
$ uv init --bare
$ uv add django gunicorn whitenoise
$ uv run django-admin startproject config .
$ uv run python manage.py startapp quotes

The trailing dot in startproject config . creates manage.py and the config package in the current directory. We add the new app to INSTALLED_APPS in config/settings.py; the other entries are generated by startproject.

config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'quotes',
]

Some files of the project directory must not get to the server: the virtual environment, the local database, the collected static files, and the file with local secrets. We list them in .gitignore; the same list tells us what to leave out when we copy the project.

.gitignore
.env
.venv/
__pycache__/
db.sqlite3
staticfiles/

The virtual environment is created on the server from pyproject.toml and uv.lock, which pins the exact versions of all packages, so the server runs the same code as the development machine.

Settings from the environment

The development machine and the server need different values for a few settings, and the secret key must not be stored in the code. We read these values from environment variables. We edit the lines generated by startproject in config/settings.py.

config/settings.py
import os
from pathlib import Path
...
SECRET_KEY = os.environ['DJANGO_SECRET_KEY']

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DJANGO_DEBUG') == '1'

ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOSTS', 'localhost').split(',')

os.environ['DJANGO_SECRET_KEY'] raises KeyError when the variable is missing, so the project never starts with a forgotten key. DEBUG is on only when the variable is 1; a missing variable means production mode, which is the safe default. ALLOWED_HOSTS is a comma-separated list. For the development machine, we put the values into the file .env.

.env
DJANGO_SECRET_KEY=local-key-for-development-only-3f9a1c7e5b2d4a6f8e0c
DJANGO_ALLOWED_HOSTS=localhost,127.0.0.1

Without the variables, manage.py fails. uv loads a file of variables with the option --env-file or, for every uv run command of the shell session, with the environment variable UV_ENV_FILE; we export it once and use plain uv run in the rest of the local steps.

$ uv run python manage.py check | tail -n 2
  File "<frozen os>", line 729, in __getitem__
KeyError: 'DJANGO_SECRET_KEY'
$ export UV_ENV_FILE=.env
$ uv run python manage.py check
System check identified no issues (0 silenced).

The quotes app

The application shows a list of quotes. The model has the text and the author.

quotes/models.py
from django.db import models


class Quote(models.Model):
    text = models.TextField()
    author = models.CharField(max_length=100)

    def __str__(self):
        return f'{self.author}: {self.text[:30]}'

The quotes come from a fixture, a JSON file in the app's fixtures directory, which we can load on any machine with loaddata.

quotes/fixtures/quotes.json
[
  {"model": "quotes.quote", "pk": 1,
   "fields": {"text": "Simple is better than complex.", "author": "Tim Peters"}},
  {"model": "quotes.quote", "pk": 2,
   "fields": {"text": "Premature optimization is the root of all evil.",
              "author": "Donald Knuth"}},
  {"model": "quotes.quote", "pk": 3,
   "fields": {"text": "Programs must be written for people to read.",
              "author": "Harold Abelson"}}
]

We create the migration, apply it, and load the fixture. The output of migrate is shortened to the line of our app.

$ uv run python manage.py makemigrations quotes
Migrations for 'quotes':
  quotes/migrations/0001_initial.py
    + Create model Quote
$ uv run python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, quotes, sessions
Running migrations:
  Applying quotes.0001_initial... OK
$ uv run python manage.py loaddata quotes
Installed 3 object(s) from 1 fixture(s)

The home page

The view lists the quotes. It also passes the id of the operating system process that handles the request, which shows us later which worker answered.

quotes/views.py
import os

from django.shortcuts import render

from .models import Quote


def home(request):
    quotes = Quote.objects.order_by('pk')
    return render(request, 'quotes/home.html', {'quotes': quotes, 'pid': os.getpid()})

The app's URLconf maps the root URL to the view.

quotes/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name='home'),
]

The project URLconf includes it next to the admin.

config/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('quotes.urls')),
]

The template links a stylesheet with the static tag and adds HTTPS to the footer when request.is_secure() is true, which becomes interesting behind a proxy.

quotes/templates/quotes/home.html
{% load static %}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Quotes</title>
  <link rel="stylesheet" href="{% static 'quotes/style.css' %}">
</head>
<body>
  <h1>Quotes</h1>
  {% for quote in quotes %}
    <blockquote>{{ quote.text }} <cite>{{ quote.author }}</cite></blockquote>
  {% endfor %}
  <footer>Process {{ pid }}{% if request.is_secure %}, HTTPS{% endif %}</footer>
</body>
</html>

The stylesheet is a static file of the app.

quotes/static/quotes/style.css
body {
  font-family: sans-serif;
  max-width: 40em;
  margin: 2em auto;
}

cite {
  display: block;
  color: #666;
}

We start the development server with debugging on, DJANGO_DEBUG=1 uv run python manage.py runserver, and ask for the page and the stylesheet in another terminal.

With DEBUG on, runserver serves the static files from the app's static directory.

$ curl -s localhost:8000/ | grep -E 'stylesheet|<blockquote|<footer'
  <link rel="stylesheet" href="/static/quotes/style.css">
    <blockquote>Simple is better than complex. <cite>Tim Peters</cite></blockquote>
    <blockquote>Premature optimization is the root of all evil. <cite>Donald Knuth</cite></blockquote>
    <blockquote>Programs must be written for people to read. <cite>Harold Abelson</cite></blockquote>
  <footer>Process 54723</footer>
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/static/quotes/style.css
200

Debugging off

We restart the development server without DJANGO_DEBUG, which is the production mode of our settings. The page still works, but the stylesheet is gone: Django serves static files only when DEBUG is on, because doing it from Python on every request is slow and the code is not hardened for the internet. An unknown URL gives a short 404 page instead of the debug page with the list of URL patterns.

Static files in production need a separate solution, and so does the server itself: the development server runs one process, reloads code, and has not been audited for security.

$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/
200
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/static/quotes/style.css
404
$ curl -s localhost:8000/missing/

<!doctype html>
<html lang="en">
<head>
  <title>Not Found</title>
</head>
<body>
  <h1>Not Found</h1><p>The requested resource was not found on this server.</p>
</body>
</html>

Gunicorn

Gunicorn is a WSGI server for production. It starts a master process, which opens the socket and manages a number of worker processes; each worker loads the Django application and handles one request at a time. The argument config.wsgi is the module with the WSGI application, generated by startproject; Gunicorn looks for the variable application in it. We start it in the project directory and stop it with Ctrl+C after the requests below.

By default Gunicorn listens on 127.0.0.1:8000 and starts one sync worker. The control socket is new in recent versions; the command gunicornc uses it to show and change the workers of a running server. The lines of the worker are in UTC, while the master logs in local time: Django sets the time zone of the process to the TIME_ZONE setting, which is UTC by default.

The curl commands below ran in another terminal while Gunicorn was running; the log after them is the output of Gunicorn, including the lines printed after Ctrl+C. The page works, and the footer shows the process id of the worker. The stylesheet still gives 404: Gunicorn runs only the Django application, which does not serve static files when DEBUG is off.

$ curl -s localhost:8000/ | grep -E '<blockquote|<footer'
    <blockquote>Simple is better than complex. <cite>Tim Peters</cite></blockquote>
    <blockquote>Premature optimization is the root of all evil. <cite>Donald Knuth</cite></blockquote>
    <blockquote>Programs must be written for people to read. <cite>Harold Abelson</cite></blockquote>
  <footer>Process 54748</footer>
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/static/quotes/style.css
404
$ uv run gunicorn config.wsgi
[2026-11-22 20:58:49 +0100] [54747] [INFO] Starting gunicorn 27.0.1
[2026-11-22 20:58:49 +0100] [54747] [INFO] Listening at: http://127.0.0.1:8000 (54747)
[2026-11-22 20:58:49 +0100] [54747] [INFO] Using worker: sync
[2026-11-22 20:58:49 +0100] [54748] [INFO] Booting worker with pid: 54748
[2026-11-22 20:58:49 +0100] [54747] [INFO] Control socket listening at /run/user/1000/gunicorn.ctl
[2026-11-22 20:58:50 +0100] [54747] [INFO] Handling signal: int
[2026-11-22 19:58:50 +0000] [54748] [INFO] Worker exiting (pid: 54748)
[2026-11-22 20:58:50 +0100] [54747] [INFO] Shutting down: Master

WhiteNoise

WhiteNoise is a middleware that serves static files from the Django application with the right headers. It is the simplest solution, and it works also on platforms where we cannot configure a web server. We add its middleware right after SecurityMiddleware.

config/settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

The middleware must come before all other middleware except SecurityMiddleware, so that requests for static files skip the session and authentication work. Next to STATIC_URL, we set STATIC_ROOT, the directory into which collectstatic copies the files, and choose the storage of WhiteNoise.

config/settings.py
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'

STORAGES = {
    'default': {
        'BACKEND': 'django.core.files.storage.FileSystemStorage',
    },
    'staticfiles': {
        'BACKEND': 'whitenoise.storage.CompressedManifestStaticFilesStorage',
    },
}

CompressedManifestStaticFilesStorage extends Django's manifest storage: every file gets a copy with a hash of its content in the name, and the static tag writes the hashed name into the page. A changed file gets a new name, so the browser may keep a file in its cache forever. WhiteNoise also writes compressed copies of the files. We collect the files.

The 131 files are our stylesheet and the files of the admin. The post-processed files are the hashed copies; Django also rewrites the URLs inside stylesheets to the hashed names.

$ uv run python manage.py collectstatic --noinput

131 static files copied to '/home/user/quotesite/staticfiles', 391 post-processed.
$ ls staticfiles/quotes/
style.3e18861f831c.css
style.css

Static files from Gunicorn

We start Gunicorn again with uv run gunicorn config.wsgi and look at the stylesheet. The -I option of curl sends a HEAD request and prints only the headers.

The page links the hashed name, and WhiteNoise serves it with a cache time of ten years and the immutable flag; the plain name is served too, but with a cache time of one minute, because its content may change. Our stylesheet is so small that compression would not save anything, so WhiteNoise did not keep a compressed copy; it keeps one only if it is at least 5 percent smaller. The admin's base.css has a .gz copy, and WhiteNoise sends it to clients that accept gzip: 5504 bytes instead of 24733. With the package brotli installed, WhiteNoise also creates Brotli copies.

$ curl -s localhost:8000/ | grep stylesheet
  <link rel="stylesheet" href="/static/quotes/style.3e18861f831c.css">
$ CSS=$(curl -s localhost:8000/ | grep -o '/static/quotes/style[^"]*')
$ curl -sI localhost:8000$CSS | grep -iE '^(HTTP|content-length|cache-control)'
HTTP/1.1 200 OK
Cache-Control: max-age=315360000, public, immutable
Content-Length: 118
$ curl -sI localhost:8000/static/quotes/style.css | grep -iE '^(HTTP|cache-control)'
HTTP/1.1 200 OK
Cache-Control: max-age=60, public
$ ls staticfiles/admin/css/ | grep '^base\.'
base.6398cd16ee3d.css
base.6398cd16ee3d.css.gz
base.css
base.css.gz
$ BASE=/static/admin/css/$(ls staticfiles/admin/css/ | grep -E '^base\.[0-9a-f]{12}\.css$')
$ curl -sI localhost:8000$BASE | grep -iE '^(content-length|content-encoding)'
Content-Length: 24733
$ curl -sI -H 'Accept-Encoding: gzip' localhost:8000$BASE | grep -iE '^(content-length|content-encoding|vary)'
Vary: Accept-Encoding
Content-Length: 5504
Content-Encoding: gzip

Logging to standard error

In production, nobody sees the yellow debug page, so errors must go into a log. Django's default logging configuration prints messages to the console only when DEBUG is on and sends errors by email to the ADMINS. We add a configuration at the end of config/settings.py that prints warnings and errors of all loggers to the standard error stream.

config/settings.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {'class': 'logging.StreamHandler'},
    },
    'root': {
        'handlers': ['console'],
        'level': 'WARNING',
    },
}

With 'disable_existing_loggers': False, the configuration adds to Django's defaults instead of replacing them. Messages of the django logger propagate to the root logger and its handler. A StreamHandler without arguments writes to the standard error stream, which Gunicorn passes on; under systemd it ends up in the journal, as we see later. Logging is covered in Django logging.

The Gunicorn configuration file

Gunicorn reads its settings from the command line or from a Python file. A file named gunicorn.conf.py in the current directory is read automatically, so we put the settings into the project directory.

gunicorn.conf.py
bind = '127.0.0.1:8000'
workers = 3
accesslog = '-'
access_log_format = '%(h)s "%(r)s" %(s)s %(b)s %(L)ss'

bind is the address to listen on; keeping it on 127.0.0.1 makes the server reachable only from the same machine, where the web server runs. workers is the number of worker processes; the Gunicorn documentation suggests two to four per CPU core as a start. accesslog = '-' writes a line for each request to the standard output, and the format prints the client address, the request line, the status, the size of the body, and the time in seconds.

Three workers boot, and the footers show which worker answered each request for the page. The request for an unknown URL is logged twice: the warning Not Found: /missing/ comes from Django through our LOGGING configuration, and the next line from Gunicorn's access log.

$ curl -s localhost:8000/ | grep '<footer'
  <footer>Process 54803</footer>
$ curl -s localhost:8000/ | grep '<footer'
  <footer>Process 54802</footer>
$ curl -s -o /dev/null localhost:8000/missing/
$ uv run gunicorn config.wsgi
[2026-11-22 20:58:52 +0100] [54800] [INFO] Starting gunicorn 27.0.1
[2026-11-22 20:58:52 +0100] [54800] [INFO] Listening at: http://127.0.0.1:8000 (54800)
[2026-11-22 20:58:52 +0100] [54800] [INFO] Using worker: sync
[2026-11-22 20:58:52 +0100] [54801] [INFO] Booting worker with pid: 54801
[2026-11-22 20:58:52 +0100] [54802] [INFO] Booting worker with pid: 54802
[2026-11-22 20:58:52 +0100] [54803] [INFO] Booting worker with pid: 54803
[2026-11-22 20:58:52 +0100] [54800] [INFO] Control socket listening at /run/user/1000/gunicorn.ctl
127.0.0.1 "GET / HTTP/1.1" 200 544 0.010311s
127.0.0.1 "GET / HTTP/1.1" 200 544 0.010506s
Not Found: /missing/
127.0.0.1 "GET /missing/ HTTP/1.1" 404 179 0.001236s
[2026-11-22 20:58:53 +0100] [54800] [INFO] Handling signal: int
[2026-11-22 19:58:53 +0000] [54801] [INFO] Worker exiting (pid: 54801)
[2026-11-22 19:58:53 +0000] [54803] [INFO] Worker exiting (pid: 54803)
[2026-11-22 19:58:53 +0000] [54802] [INFO] Worker exiting (pid: 54802)
[2026-11-22 20:58:53 +0100] [54800] [INFO] Shutting down: Master

The server

The rest of the article runs on a Debian 12 server with Nginx installed (sudo apt install nginx). We log in as a user with sudo rights. First we install uv for all users into /usr/local/bin with its installer script.

The application should not run as root, nor as our own user. We create a system user quotes with the home directory /srv/quotes, where the application will live, and without a login shell.

$ curl -LsSf https://astral.sh/uv/install.sh | sudo env UV_INSTALL_DIR=/usr/local/bin sh
downloading uv 0.13.9 x86_64-unknown-linux-gnu
installing to /usr/local/bin
  uv
  uvx
everything's installed!
$ uv --version
uv 0.13.9 (x86_64-unknown-linux-gnu)
$ sudo useradd --system --create-home --home-dir /srv/quotes --shell /usr/sbin/nologin quotes
$ ls -ld /srv/quotes
drwxr-xr-x 2 quotes quotes 4096 Nov 22 20:59 /srv/quotes

Installing the application

We copy the project to /srv/quotes/app without the files listed in .gitignore, for example with git clone from the project's repository or with rsync --exclude from the development machine, and make the user quotes its owner. Then we let uv create the virtual environment as that user.

uv sync --frozen installs exactly the versions from uv.lock and fails instead of updating the lock file; --no-dev skips development dependencies. The server has Python 3.14, but the project requires 3.15, so uv downloads a Python build into the home directory of quotes.

$ cd /srv/quotes/app
$ ls -A
.gitignore
config
gunicorn.conf.py
manage.py
pyproject.toml
quotes
uv.lock
$ sudo -u quotes uv sync --frozen --no-dev
Downloading cpython-3.15.2-linux-x86_64-gnu (download) (36.6MiB)
 Downloaded cpython-3.15.2-linux-x86_64-gnu (download)
Using CPython 3.15.2
Creating virtual environment at: .venv
Downloading django (8.0MiB)
 Downloaded django
Prepared 5 packages in 3.19s
Installed 5 packages in 90ms
 + asgiref==3.13.0
 + django==6.1.3
 + gunicorn==27.0.1
 + sqlparse==0.6.1
 + whitenoise==6.12.0

Configuration on the server

The listings with a plain header from now on are files on the server, outside of the project. The settings for the server go into the file /etc/quotes/env, which we create with sudo and an editor.

/etc/quotes/env
DJANGO_ALLOWED_HOSTS=quotes.example.com

The secret key is generated on the server and appended to the file, so that it never appears on the screen or in the repository. The file is readable by the group quotes and writable only by root.

$ echo "DJANGO_SECRET_KEY=$(python3 -c 'import secrets; print(secrets.token_urlsafe(50))')" | sudo tee -a /etc/quotes/env > /dev/null
$ sudo chown root:quotes /etc/quotes/env
$ sudo chmod 640 /etc/quotes/env
$ ls -l /etc/quotes/env
-rw-r----- 1 root quotes 126 Nov 22 20:59 /etc/quotes/env

The database and static files

The management commands run as quotes with the variables from the file. We apply the migrations, collect the static files, load the quotes, and create an administrator for the admin site.

createsuperuser --noinput takes the password from the variable DJANGO_SUPERUSER_PASSWORD; on a real server, pick a strong password and do not leave it in the shell history. The SQLite database is created in the project directory, which belongs to quotes. For a site with more traffic, a server database such as PostgreSQL is the usual choice; see Django database configuration.

$ sudo -u quotes uv run --env-file /etc/quotes/env python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, quotes, sessions
Running migrations:
  Applying quotes.0001_initial... OK
$ sudo -u quotes uv run --env-file /etc/quotes/env python manage.py collectstatic --noinput

131 static files copied to '/srv/quotes/app/staticfiles', 391 post-processed.
$ sudo -u quotes uv run --env-file /etc/quotes/env python manage.py loaddata quotes
Installed 3 object(s) from 1 fixture(s)
$ sudo -u quotes DJANGO_SUPERUSER_PASSWORD=Kq7-not-a-real-password uv run --env-file /etc/quotes/env python manage.py createsuperuser --noinput --username admin --email admin@example.com
Superuser created successfully.

A systemd service

systemd starts Gunicorn at boot, restarts it after a crash, and collects its output in the journal. We describe the service in the unit file /etc/systemd/system/quotes.service.

/etc/systemd/system/quotes.service
[Unit]
Description=Quotes Django application
After=network.target

[Service]
Type=notify
NotifyAccess=main
User=quotes
Group=quotes
WorkingDirectory=/srv/quotes/app
EnvironmentFile=/etc/quotes/env
ExecStart=/srv/quotes/app/.venv/bin/gunicorn config.wsgi
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=10
Restart=on-failure
PrivateTmp=true
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target

Type=notify makes systemd wait until Gunicorn reports that it is ready, which Gunicorn does through the socket in NOTIFY_SOCKET. The service runs as quotes in the project directory, with the variables from the environment file. ExecStart calls Gunicorn from the virtual environment directly, without uv. ExecReload sends HUP to the master, which starts new workers with fresh code and stops the old ones gracefully. KillMode=mixed sends the stop signal to the master only and lets it stop its workers, and Restart=on-failure restarts the service when it dies. PrivateTmp and NoNewPrivileges are two simple hardening options.

systemd-analyze verify prints nothing for a valid unit. enable --now starts the service and enables it at boot. The status shows the master and three workers, and the status text that Gunicorn sent to systemd.

$ systemd-analyze verify /etc/systemd/system/quotes.service
$ sudo systemctl daemon-reload
$ sudo systemctl enable --now quotes
Created symlink /etc/systemd/system/multi-user.target.wants/quotes.service → /etc/systemd/system/quotes.service.
$ systemctl status quotes --no-pager -n 0
● quotes.service - Quotes Django application
     Loaded: loaded (/etc/systemd/system/quotes.service; enabled; preset: enabled)
     Active: active (running) since Sun 2026-11-22 20:59:22 CET; 1s ago
   Main PID: 421 (gunicorn)
     Status: "Gunicorn arbiter booted"
      Tasks: 5 (limit: 120)
     Memory: 112.7M
        CPU: 559ms
     CGroup: /system.slice/quotes.service
             ├─421 /srv/quotes/app/.venv/bin/python /srv/quotes/app/.venv/bin/gunicorn config.wsgi
             ├─422 /srv/quotes/app/.venv/bin/python /srv/quotes/app/.venv/bin/gunicorn config.wsgi
             ├─423 /srv/quotes/app/.venv/bin/python /srv/quotes/app/.venv/bin/gunicorn config.wsgi
             └─424 /srv/quotes/app/.venv/bin/python /srv/quotes/app/.venv/bin/gunicorn config.wsgi

Logs in the journal

We ask Gunicorn directly with curl. The application accepts only the host quotes.example.com, so the first request sends it in the Host header; the second request uses localhost:8000 and is refused with 400.

The journal of the service has the reason. The warning with the traceback comes from the django.security.DisallowedHost logger through our logging configuration, and the last line is Gunicorn's access log. journalctl -f -u quotes follows the log live.

$ curl -s -H 'Host: quotes.example.com' localhost:8000/ | grep -E '<footer'
  <footer>Process 423</footer>
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/
400
$ sudo journalctl -u quotes --no-pager -o short -n 12
Nov 22 20:59:24 web1 gunicorn[423]: Invalid HTTP_HOST header: 'localhost:8000'. You may need to add 'localhost' to ALLOWED_HOSTS.
Nov 22 20:59:24 web1 gunicorn[423]: Traceback (most recent call last):
Nov 22 20:59:24 web1 gunicorn[423]:   File "/srv/quotes/app/.venv/lib/python3.15/site-packages/django/core/handlers/exception.py", line 56, in inner
Nov 22 20:59:24 web1 gunicorn[423]:     response = get_response(request)
Nov 22 20:59:24 web1 gunicorn[423]:   File "/srv/quotes/app/.venv/lib/python3.15/site-packages/django/utils/deprecation.py", line 441, in __call__
Nov 22 20:59:24 web1 gunicorn[423]:     response = self.process_request(request)
Nov 22 20:59:24 web1 gunicorn[423]:   File "/srv/quotes/app/.venv/lib/python3.15/site-packages/django/middleware/common.py", line 48, in process_request
Nov 22 20:59:24 web1 gunicorn[423]:     host = request.get_host()
Nov 22 20:59:24 web1 gunicorn[423]:   File "/srv/quotes/app/.venv/lib/python3.15/site-packages/django/http/request.py", line 210, in get_host
Nov 22 20:59:24 web1 gunicorn[423]:     raise DisallowedHost(msg)
Nov 22 20:59:24 web1 gunicorn[423]: django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'localhost:8000'. You may need to add 'localhost' to ALLOWED_HOSTS.
Nov 22 20:59:24 web1 gunicorn[423]: 127.0.0.1 "GET / HTTP/1.1" 400 143 0.014853s

Restarting after a crash

To see Restart=on-failure at work, we kill the master process with SIGKILL, which cannot be caught. systemctl show gives the id of the main process.

systemd notices that the main process died, kills the remaining workers, and starts the service again right away; two seconds later it is active. A worker that crashes is replaced by the Gunicorn master itself, without systemd.

$ sudo kill -9 $(systemctl show -p MainPID --value quotes)
$ systemctl is-active quotes
active
$ sudo journalctl -u quotes --no-pager -o short --since '20:59:24' | grep systemd
Nov 22 20:59:25 web1 systemd[1]: quotes.service: Main process exited, code=killed, status=9/KILL
Nov 22 20:59:25 web1 systemd[1]: quotes.service: Killing process 422 (gunicorn) with signal SIGKILL.
Nov 22 20:59:25 web1 systemd[1]: quotes.service: Killing process 423 (gunicorn) with signal SIGKILL.
Nov 22 20:59:25 web1 systemd[1]: quotes.service: Killing process 424 (gunicorn) with signal SIGKILL.
Nov 22 20:59:25 web1 systemd[1]: quotes.service: Failed with result 'signal'.
Nov 22 20:59:25 web1 systemd[1]: quotes.service: Scheduled restart job, restart counter is at 1.
Nov 22 20:59:25 web1 systemd[1]: Stopped quotes.service - Quotes Django application.
Nov 22 20:59:25 web1 systemd[1]: Starting quotes.service - Quotes Django application...
Nov 22 20:59:25 web1 systemd[1]: Started quotes.service - Quotes Django application.

Nginx as a reverse proxy

Nginx accepts the connections from the internet and passes them to Gunicorn. It buffers slow clients, so a Gunicorn worker is busy only while Django works, not while a client on a slow line sends its request or reads the response. We create the site configuration /etc/nginx/sites-available/quotes.

/etc/nginx/sites-available/quotes
server {
    listen 80;
    server_name quotes.example.com;

    client_max_body_size 10m;

    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;
    }
}

The server block answers requests for quotes.example.com on port 80 and passes them to Gunicorn. proxy_set_header passes the original host, the client address, and the scheme, which Nginx would otherwise replace with its own view of the connection. client_max_body_size limits uploads. Static files go to Gunicorn too, where WhiteNoise handles them; a location /static/ block with an alias to the staticfiles directory would let Nginx serve them itself.

We enable the site with a link in sites-enabled, test the configuration, and reload Nginx. The domain does not point to our server, so for the tests we add it to /etc/hosts on the server.

The page now comes through Nginx, which adds its Server header; the X-Frame-Options header comes from Django. A request with another host name goes to Nginx's default site, which answers itself, so Django is not even asked.

$ echo '127.0.0.1 quotes.example.com' | sudo tee -a /etc/hosts
$ sudo ln -s /etc/nginx/sites-available/quotes /etc/nginx/sites-enabled/
$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
$ sudo systemctl reload nginx
$ curl -sI http://quotes.example.com/ | grep -iE '^(HTTP|server|x-frame)'
HTTP/1.1 200 OK
Server: nginx/1.22.1
X-Frame-Options: DENY
$ curl -s http://quotes.example.com/ | grep '<footer'
  <footer>Process 473</footer>
$ curl -s -o /dev/null -w '%{http_code}\n' http://localhost/
200

A TLS certificate

A public site needs HTTPS. On a real server, a free certificate from Let's Encrypt is obtained with a client such as Certbot, which proves that we control the domain and renews the certificate automatically. Our test domain is not public, so we create a self-signed certificate with OpenSSL instead; browsers would warn about it, and curl needs the certificate to trust it.

The key is readable only by root; Nginx reads it while it still runs as root, before it switches to the user www-data.

$ sudo openssl req -x509 -newkey rsa:2048 -nodes -days 365 -subj /CN=quotes.example.com -addext subjectAltName=DNS:quotes.example.com -keyout /etc/ssl/private/quotes.key -out /etc/ssl/certs/quotes.crt 2> /dev/null
$ sudo ls -l /etc/ssl/private/quotes.key /etc/ssl/certs/quotes.crt
-rw-r--r-- 1 root root 1180 Nov 22 20:59 /etc/ssl/certs/quotes.crt
-rw------- 1 root root 1704 Nov 22 20:59 /etc/ssl/private/quotes.key

HTTPS in Nginx

We replace the site configuration. The server block on port 80 now only redirects to HTTPS, and a new block on port 443 handles TLS and passes the requests to Gunicorn.

/etc/nginx/sites-available/quotes
server {
    listen 80;
    server_name quotes.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name quotes.example.com;

    ssl_certificate /etc/ssl/certs/quotes.crt;
    ssl_certificate_key /etc/ssl/private/quotes.key;

    client_max_body_size 10m;

    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;
    }
}

listen 443 ssl turns on TLS with the certificate and the key. The header X-Forwarded-Proto is now https, because $scheme is the scheme of the client's connection.

The plain HTTP request is redirected. The page over HTTPS shows HTTPS in the footer, so request.is_secure() is true, although Gunicorn gets plain HTTP from Nginx. Gunicorn trusts the X-Forwarded-Proto header from the addresses in its setting forwarded_allow_ips, which is 127.0.0.1,::1 by default, and sets the scheme of the request accordingly. The login to the admin works: the CSRF check compares the Origin header with the scheme and host of the request, and both are right. The last command prints the domain, the secure flag, and the name of each cookie in the cookie jar of curl: the cookies are not marked secure.

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
$ sudo systemctl reload nginx
$ curl -sI http://quotes.example.com/ | grep -iE '^(HTTP|location)'
HTTP/1.1 301 Moved Permanently
Location: https://quotes.example.com/
$ curl -s --cacert /etc/ssl/certs/quotes.crt https://quotes.example.com/ | grep '<footer'
  <footer>Process 472, HTTPS</footer>
$ curl -s -c jar --cacert /etc/ssl/certs/quotes.crt -o /dev/null https://quotes.example.com/admin/login/
$ TOKEN=$(grep csrftoken jar | cut -f 7)
$ curl -s -b jar -c jar --cacert /etc/ssl/certs/quotes.crt -o /dev/null -w '%{http_code} %{redirect_url}\n' -H 'Origin: https://quotes.example.com' -H 'Referer: https://quotes.example.com/admin/login/' -d "csrfmiddlewaretoken=$TOKEN&username=admin&password=Kq7-not-a-real-password" https://quotes.example.com/admin/login/?next=/admin/
302 https://quotes.example.com/admin/
$ grep -E 'csrftoken|sessionid' jar | cut -f 1,4,6
#HttpOnly_quotes.example.com	FALSE	sessionid
quotes.example.com	FALSE	csrftoken

Django behind an HTTPS proxy

We add the HTTPS settings at the end of config/settings.py, switched on with a variable, so that the development machine keeps working over plain HTTP.

config/settings.py
if os.environ.get('DJANGO_HTTPS') == '1':
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    SECURE_HSTS_SECONDS = 3600

SECURE_PROXY_SSL_HEADER tells Django itself to trust the header; it is needed when the application server does not interpret it, for example when Gunicorn and Nginx run on different machines. The proxy must always set or remove the header, otherwise a client could send it. SECURE_SSL_REDIRECT redirects plain HTTP requests that reach Django. The two cookie settings add the Secure flag, so the browser never sends the cookies over plain HTTP, and SECURE_HSTS_SECONDS tells browsers to use only HTTPS for the site for the given time; start with a short time, because a mistake cannot be taken back until it expires.

We copy the new settings to the server and set the variable. systemd reads the environment file only when it starts the service, and HUP does not restart the master, so we restart the service instead of reloading it.

The response now has the Strict-Transport-Security header, and after a new login, both cookies carry the secure flag.

$ echo DJANGO_HTTPS=1 | sudo tee -a /etc/quotes/env
$ sudo systemctl restart quotes
$ curl -s --cacert /etc/ssl/certs/quotes.crt https://quotes.example.com/ | grep '<footer'
  <footer>Process 666, HTTPS</footer>
$ curl -sI --cacert /etc/ssl/certs/quotes.crt https://quotes.example.com/ | grep -i '^strict'
Strict-Transport-Security: max-age=3600
$ rm jar
$ curl -s -c jar --cacert /etc/ssl/certs/quotes.crt -o /dev/null https://quotes.example.com/admin/login/
$ TOKEN=$(grep csrftoken jar | cut -f 7)
$ curl -s -b jar -c jar --cacert /etc/ssl/certs/quotes.crt -o /dev/null -w '%{http_code} %{redirect_url}\n' -H 'Origin: https://quotes.example.com' -H 'Referer: https://quotes.example.com/admin/login/' -d "csrfmiddlewaretoken=$TOKEN&username=admin&password=Kq7-not-a-real-password" https://quotes.example.com/admin/login/?next=/admin/
302 https://quotes.example.com/admin/
$ grep -E 'csrftoken|sessionid' jar | cut -f 1,4,6
#HttpOnly_quotes.example.com	TRUE	sessionid
quotes.example.com	TRUE	csrftoken

Checking the deployment

The command check --deploy runs extra system checks for production. We run it on the server with the production environment.

The check fails with an error: the MAILERS setting generated by startproject in Django 6.1 uses the console backend, which prints email to the standard output instead of sending it. The two warnings concern HSTS: SECURE_HSTS_INCLUDE_SUBDOMAINS extends the policy to all subdomains, and SECURE_HSTS_PRELOAD allows the domain to be put on the preload list built into browsers. Both are hard to undo and depend on the whole domain, not only this site, so we leave them off and accept the warnings.

$ sudo -u quotes uv run --env-file /etc/quotes/env python manage.py check --deploy
SystemCheckError: System check identified some issues:

ERRORS:
?: (mail.E001) Your MAILERS setting uses a development-only email backend in the 'default' entry (django.core.mail.backends.console.EmailBackend).
	HINT: Use a production-ready email backend, such as the SMTP backend, otherwise email will not be sent.

WARNINGS:
?: (security.W005) You have not set the SECURE_HSTS_INCLUDE_SUBDOMAINS setting to True. Without this, your site is potentially vulnerable to attack via an insecure connection to a subdomain. Only set this to True if you are certain that all subdomains of your domain should be served exclusively via SSL.
?: (security.W021) You have not set the SECURE_HSTS_PRELOAD setting to True. Without this, your site cannot be submitted to the browser preload list.

System check identified 3 issues (0 silenced).

Email in production

We replace the generated MAILERS setting with one that keeps the console backend for development and uses SMTP in production.

config/settings.py
if DEBUG:
    MAILERS = {
        'default': {
            'BACKEND': 'django.core.mail.backends.console.EmailBackend',
        },
    }
else:
    MAILERS = {
        'default': {
            'BACKEND': 'django.core.mail.backends.smtp.EmailBackend',
            'OPTIONS': {
                'host': os.environ.get('DJANGO_SMTP_HOST', 'localhost'),
                'port': int(os.environ.get('DJANGO_SMTP_PORT', '25')),
            },
        },
    }

The SMTP backend sends email through the mail server given in the options; the defaults point to a mail server on the same machine. For a mail provider, add the username, the password, and use_tls options from more environment variables. Sending email is covered in Django email. We copy the settings to the server again.

Only the two HSTS warnings are left. The settings change needs no new environment variables, so a reload is enough.

$ sudo -u quotes uv run --env-file /etc/quotes/env python manage.py check --deploy
System check identified some issues:

WARNINGS:
?: (security.W005) You have not set the SECURE_HSTS_INCLUDE_SUBDOMAINS setting to True. Without this, your site is potentially vulnerable to attack via an insecure connection to a subdomain. Only set this to True if you are certain that all subdomains of your domain should be served exclusively via SSL.
?: (security.W021) You have not set the SECURE_HSTS_PRELOAD setting to True. Without this, your site cannot be submitted to the browser preload list.

System check identified 2 issues (0 silenced).
$ sudo systemctl reload quotes

Deploying a new version

A deployment repeats a few steps: copy the new code, update the packages, apply new migrations, collect the static files, and reload Gunicorn. We change the heading of the template on the development machine and copy the project to the server.

quotes/templates/quotes/home.html
  <h1>Quotes for programmers</h1>

On the server, we run the steps in the project directory. Each step is cheap when there is nothing to do, so it is safe to run all of them on every deployment; they are good candidates for a small script.

The page shows the new heading. The journal shows the graceful reload: the master handles HUP, boots three new workers with the new code, and tells the old ones to exit; an old worker finishes its current request first, so no request is lost. The output is filtered to hide the repeated control socket lines.

$ sudo -u quotes uv sync --frozen --no-dev
Checked 5 packages in 0.07ms
$ sudo -u quotes uv run --env-file /etc/quotes/env python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, quotes, sessions
Running migrations:
  No migrations to apply.
$ sudo -u quotes uv run --env-file /etc/quotes/env python manage.py collectstatic --noinput

0 static files copied to '/srv/quotes/app/staticfiles', 131 unmodified, 360 post-processed.
$ sudo systemctl reload quotes
$ curl -s --cacert /etc/ssl/certs/quotes.crt https://quotes.example.com/ | grep -E '<h1>|<footer'
  <h1>Quotes for programmers</h1>
  <footer>Process 807, HTTPS</footer>
$ sudo journalctl -u quotes --no-pager -o short --since '20:59:35' | grep -v 'Control socket'
Nov 22 20:59:36 web1 systemd[1]: Reloading quotes.service - Quotes Django application...
Nov 22 20:59:36 web1 gunicorn[663]: [2026-11-22 20:59:36 +0100] [663] [INFO] Handling signal: hup
Nov 22 20:59:36 web1 gunicorn[663]: [2026-11-22 20:59:36 +0100] [663] [INFO] Hang up: Master
Nov 22 20:59:36 web1 systemd[1]: Reloaded quotes.service - Quotes Django application.
Nov 22 20:59:36 web1 gunicorn[803]: [2026-11-22 20:59:36 +0100] [803] [INFO] Booting worker with pid: 803
Nov 22 20:59:36 web1 gunicorn[805]: [2026-11-22 20:59:36 +0100] [805] [INFO] Booting worker with pid: 805
Nov 22 20:59:36 web1 gunicorn[735]: [2026-11-22 19:59:36 +0000] [735] [INFO] Worker exiting (pid: 735)
Nov 22 20:59:36 web1 gunicorn[731]: [2026-11-22 19:59:36 +0000] [731] [INFO] Worker exiting (pid: 731)
Nov 22 20:59:36 web1 gunicorn[733]: [2026-11-22 19:59:36 +0000] [733] [INFO] Worker exiting (pid: 733)
Nov 22 20:59:36 web1 gunicorn[807]: [2026-11-22 20:59:36 +0100] [807] [INFO] Booting worker with pid: 807
Nov 22 20:59:38 web1 gunicorn[807]: 127.0.0.1 "GET / HTTP/1.0" 200 565 0.010064s

ASGI workers

The setup above runs Django through WSGI. A project with asynchronous views, described in Async Django, profits from an ASGI server. Gunicorn 27 has its own ASGI worker class, so we only change the configuration file.

gunicorn.conf.py
bind = '127.0.0.1:8000'
workers = 3
worker_class = 'asgi'
accesslog = '-'
access_log_format = '%(h)s "%(r)s" %(s)s %(b)s %(L)ss'

The worker class asgi runs an asyncio event loop in each worker. The application is now the ASGI application from config/asgi.py, so we change one line in the unit file.

/etc/systemd/system/quotes.service
ExecStart=/srv/quotes/app/.venv/bin/gunicorn config.asgi

Another common choice is Uvicorn: the package uvicorn-worker provides the worker class uvicorn_worker.UvicornWorker for Gunicorn, and Uvicorn can also run its own processes with --workers. Nginx needs no change. We copy the configuration to the server, reload the units, and restart the service, because the worker class cannot change with a reload.

The journal shows Using worker: asgi and a line of each worker's server; the page and the logging work as before.

$ sudo systemctl daemon-reload
$ sudo systemctl restart quotes
$ curl -s --cacert /etc/ssl/certs/quotes.crt https://quotes.example.com/ | grep -E '<footer'
  <footer>Process 886, HTTPS</footer>
$ curl -s --cacert /etc/ssl/certs/quotes.crt -o /dev/null https://quotes.example.com/missing/
$ sudo journalctl -u quotes --no-pager -o short --since '20:59:38'
Nov 22 20:59:38 web1 gunicorn[807]: 127.0.0.1 "GET / HTTP/1.0" 200 565 0.010064s
Nov 22 20:59:39 web1 systemd[1]: Stopping quotes.service - Quotes Django application...
Nov 22 20:59:39 web1 gunicorn[663]: [2026-11-22 20:59:39 +0100] [663] [INFO] Handling signal: term
Nov 22 20:59:39 web1 gunicorn[807]: [2026-11-22 19:59:39 +0000] [807] [INFO] Worker exiting (pid: 807)
Nov 22 20:59:39 web1 gunicorn[805]: [2026-11-22 19:59:39 +0000] [805] [INFO] Worker exiting (pid: 805)
Nov 22 20:59:39 web1 gunicorn[803]: [2026-11-22 19:59:39 +0000] [803] [INFO] Worker exiting (pid: 803)
Nov 22 20:59:39 web1 gunicorn[663]: [2026-11-22 20:59:39 +0100] [663] [INFO] Shutting down: Master
Nov 22 20:59:39 web1 systemd[1]: quotes.service: Deactivated successfully.
Nov 22 20:59:39 web1 systemd[1]: Stopped quotes.service - Quotes Django application.
Nov 22 20:59:39 web1 systemd[1]: quotes.service: Consumed 3.044s CPU time.
Nov 22 20:59:39 web1 systemd[1]: Starting quotes.service - Quotes Django application...
Nov 22 20:59:39 web1 gunicorn[883]: [2026-11-22 20:59:39 +0100] [883] [INFO] Starting gunicorn 27.0.1
Nov 22 20:59:39 web1 gunicorn[883]: [2026-11-22 20:59:39 +0100] [883] [INFO] Listening at: http://127.0.0.1:8000 (883)
Nov 22 20:59:39 web1 gunicorn[883]: [2026-11-22 20:59:39 +0100] [883] [INFO] Using worker: asgi
Nov 22 20:59:39 web1 systemd[1]: Started quotes.service - Quotes Django application.
Nov 22 20:59:39 web1 gunicorn[884]: [2026-11-22 20:59:39 +0100] [884] [INFO] Booting worker with pid: 884
Nov 22 20:59:40 web1 gunicorn[885]: [2026-11-22 20:59:40 +0100] [885] [INFO] Booting worker with pid: 885
Nov 22 20:59:40 web1 gunicorn[886]: [2026-11-22 20:59:40 +0100] [886] [INFO] Booting worker with pid: 886
Nov 22 20:59:40 web1 gunicorn[884]: [2026-11-22 19:59:40 +0000] [884] [INFO] ASGI server listening on http://127.0.0.1:8000
Nov 22 20:59:40 web1 gunicorn[885]: [2026-11-22 19:59:40 +0000] [885] [INFO] ASGI server listening on http://127.0.0.1:8000
Nov 22 20:59:40 web1 gunicorn[883]: [2026-11-22 20:59:40 +0100] [883] [INFO] Control socket listening at /srv/quotes/.gunicorn/gunicorn.ctl
Nov 22 20:59:40 web1 gunicorn[886]: [2026-11-22 19:59:40 +0000] [886] [INFO] ASGI server listening on http://127.0.0.1:8000
Nov 22 20:59:41 web1 gunicorn[886]: 127.0.0.1 "GET / HTTP/1.0" 200 565 0.011451s
Nov 22 20:59:41 web1 gunicorn[886]: Not Found: /missing/
Nov 22 20:59:41 web1 gunicorn[886]: 127.0.0.1 "GET /missing/ HTTP/1.0" 404 179 0.003641s

Source

Django documentation: How to deploy Django

Django documentation: Deployment checklist

Gunicorn documentation

WhiteNoise documentation

Nginx: ngx_http_proxy_module

systemd.service manual

In this article we have deployed a Django project: we read the settings from environment variables, ran the project with Gunicorn, served static files with WhiteNoise, logged to the standard error stream, installed the project on a Debian server with uv, ran it as a systemd service, put Nginx with HTTPS in front of it, configured Django for the proxy, checked the deployment, deployed a new version with a graceful reload, and switched to ASGI workers. Related articles are Django settings and environment, Django static files, Django logging, Django security, Async Django, and Docker and Django.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Django tutorials.