Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 77 ยท Deployment and Production

Deploying Django

Deploy Django safely: the production checklist, environment variables, ALLOWED_HOSTS, Gunicorn or Uvicorn, Nginx, WhiteNoise static files, database settings and health checks.

python manage.py runserver is a wonderful development tool and a terrible production server. It handles one thing at a time, reloads on every edit, shows detailed errors to anyone who triggers one, and was never audited for hostile traffic. Putting a site on the internet means replacing it with a proper stack and tightening your settings.

This lesson walks through that move. You will learn the production checklist, how to keep secrets out of your code with environment variables, how an application server such as Gunicorn or Uvicorn and a reverse proxy such as Nginx fit together, how to serve static files with WhiteNoise, how to configure the database, and how to add health checks. Server commands and configuration files are shown read-only, since they need a real machine. The settings logic runs live: you will validate a configuration the same way check --deploy does.

The production architecture

A typical small-to-medium Django deployment has four layers:

flowchart LR
    U["Browser"] -->|"HTTPS"| N["Nginx<br/>reverse proxy, TLS"]
    N -->|"HTTP on localhost"| G["Gunicorn or Uvicorn<br/>app server, several workers"]
    G --> D["Django app"]
    D --> P[("PostgreSQL")]
    N -.->|"/static/"| S["Static files<br/>(or WhiteNoise / CDN)"]

The proxy terminates HTTPS and forwards requests to worker processes that run Django; the database lives separately.

  • Reverse proxy (Nginx, Caddy or a cloud load balancer): terminates TLS, buffers slow clients, serves static files efficiently and forwards other requests.
  • Application server (Gunicorn for WSGI, Uvicorn or Daphne for ASGI): runs several worker processes of your Django code.
  • Django: your project, configured by environment-specific settings.
  • Database and friends: PostgreSQL (or MySQL), plus Redis for caching or queues when you need them.

You can also skip server administration entirely by using a platform (Heroku-style PaaS, Fly.io, Railway, Render, Google Cloud Run, AWS App Runner). The concepts below still apply; the platform just provides the proxy and process management for you.

The production checklist

Before the first public request, make sure each of these is true:

Item Setting or action
Debug off DEBUG = False (debug pages leak settings, paths and source code)
Secret key secret SECRET_KEY unique, long, random and loaded from the environment
Hosts restricted ALLOWED_HOSTS = ["example.com", "www.example.com"]
HTTPS everywhere SECURE_SSL_REDIRECT, HSTS, secure cookies
Real database PostgreSQL or MySQL, not a SQLite file on an ephemeral disk
Static files collected collectstatic run during the build
Errors visible to you Logging to stdout and an error tracker such as Sentry
Migrations applied migrate run on each release, before the new code takes traffic
Backups tested Restore a backup at least once
Checks pass python manage.py check --deploy shows no warnings

Settings and environment variables

Settings that differ between your laptop and production, or that are secret, should not be written into settings.py. The common solution is environment variables (the "twelve-factor" approach, see also Projects, Apps and Settings): the code stays identical everywhere and each environment supplies its own values.

Python
# settings.py (read-only)
import os

SECRET_KEY = os.environ["SECRET_KEY"]           # missing key -> crash at startup, on purpose
DEBUG = os.environ.get("DEBUG", "false").lower() == "true"
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "").split(",")

Failing fast when SECRET_KEY is missing is a feature: you notice a bad deployment immediately instead of running with a default that anyone could guess. Packages such as django-environ or python-decouple wrap this pattern, and a hand-written helper is only a few lines. The example below builds one, including parsing of a typical DATABASE_URL. It reads from a dictionary standing in for os.environ, so the output is the same on every run.

Python A small environment-variable reader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice three details: the percent-encoded @ in the password is decoded, booleans are parsed from words instead of relying on truthy strings ("false" is a non-empty string and therefore truthy in Python!), and a missing required variable raises an error with the variable's name.

Never commit secrets to Git, even in a private repository. Keep a .env file in .gitignore, document the variable names in a committed .env.example, and set real values in your hosting platform's secret store. If a key ever leaks, rotate it: changing SECRET_KEY invalidates sessions and signed tokens, which is an acceptable price (the next section shows how to rotate it without signing everyone out).

Generating, loading and rotating SECRET_KEY

SECRET_KEY is the one value that makes Django's signatures unforgeable. Django uses it to sign session data and cookies, password-reset links, CSRF tokens and anything you sign with django.core.signing. Anyone who knows the key can forge a valid session or reset link, which is why it must be long, random and different in every environment. startproject writes a throwaway django-insecure-... key into settings.py for development only; production needs its own.

Generating one. Use Django's own generator, either in a Python shell or in a one-liner, and store the result in your platform's secret store:

Terminal
# read-only
python -c "from django.core.management.utils import get_random_secret_key as k; print(k())"

check --deploy warns (security.W009) when the key is short, has too few distinct characters or still starts with django-insecure-.

Loading it. Read the key from the environment, as shown earlier. For more than a couple of variables, a small library saves boilerplate: django-environ reads a .env file, converts types (bool, int, list) and even parses URLs like DATABASE_URL into the dictionaries Django expects (python-decouple is a lighter alternative):

Python
# settings.py (read-only; pip install django-environ)
import environ

env = environ.Env(DEBUG=(bool, False))
environ.Env.read_env(BASE_DIR / ".env")            # a real environment variable always wins over the file

SECRET_KEY = env("SECRET_KEY")                     # no default: a missing key fails at start-up
DEBUG = env("DEBUG")
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS")
DATABASES = {"default": env.db()}                  # parses DATABASE_URL

Keep .env out of version control (.gitignore) and commit a .env.example with fake values so a teammate knows which variables to set. In production, skip the file and set real environment variables in the platform's configuration page, so the secrets never touch the repository or the disk image.

Rotating it. If a key may have leaked, or as routine hygiene, you want to replace it. Simply swapping the value signs out every user and invalidates every outstanding reset link and signed token at once. Since Django 4.1 you can rotate gently: put the new key in SECRET_KEY and the old one (or several) in SECRET_KEY_FALLBACKS. New signatures use the new key, while existing ones still verify against the fallbacks. After the longest-lived signed value has expired (a session lifetime, a token's maximum age), remove the old key from the list. Two details matter: fallbacks only help values signed through Django's signing machinery, so a hand-rolled hmac using settings.SECRET_KEY directly will not accept the old key; and if the key leaked, do not keep it as a fallback longer than you must, because it can still be used to forge values that verify.

The example below runs all three pieces for real: the generator, a .env file parsed by django-environ, and a rotation with and without fallbacks.

Python get_random_secret_key, django-environ and SECRET_KEY_FALLBACKS

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second half shows why SECRET_KEY_FALLBACKS exists: signed with the old key, the token breaks the moment only the new key is configured, and verifies again when the old key is listed as a fallback. Treat environment variables as a contract: list every variable your project needs in .env.example and in the README, fail fast when a required one is missing, and never log their values.

ALLOWED_HOSTS, HTTPS and cookies

With DEBUG = False, Django refuses requests whose Host header is not listed in ALLOWED_HOSTS. This stops host-header attacks, where an attacker makes your site generate password-reset links that point to their domain. List your real domains, never "*".

When Nginx terminates TLS, Django only sees plain HTTP from the proxy. Tell Django how to detect the original scheme, or it will redirect forever and build http:// links:

Python
# settings.py (read-only)
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")   # only if your proxy sets it
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000          # start small (e.g. 3600) while testing!
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_TRUSTED_ORIGINS = ["https://example.com"]

Only trust X-Forwarded-Proto if your proxy always overwrites it, otherwise clients could forge it. HSTS tells browsers to use HTTPS only for the given period, which is hard to undo, so ramp it up gradually. These settings are covered further in Security in Django.

Checking your settings automatically

Django can audit your configuration with python manage.py check --deploy. It reports warnings such as "DEBUG is true", "no HSTS", or "SECRET_KEY looks insecure", each with an identifier like security.W018. Running it in CI turns the checklist into an automatic gate.

The command is a thin wrapper around django.core.checks.run_checks, which you can call from Python. The example below checks an insecure development configuration, then the same project with production values applied through override_settings. It prints warning identifiers and our own short descriptions, so the output does not depend on the exact wording of any Django release.

Python Validate settings like check --deploy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first run lists seven findings, the hardened configuration passes cleanly, and removing a single setting brings exactly one warning back. That is the whole idea of the deployment check: a precise, repeatable list of what is still unsafe.

Application servers: Gunicorn and Uvicorn

Django's development server is replaced by a production-grade application server that starts several worker processes, restarts crashed ones and handles many connections.

For classic WSGI deployments, Gunicorn is the default choice:

TEXT
pip install gunicorn
gunicorn mysite.wsgi:application --bind 127.0.0.1:8000 --workers 3 --timeout 30

A common starting point is workers = 2 ร— CPU cores + 1, then adjust by watching memory and CPU. For ASGI projects (async views, WebSockets) run Uvicorn, either directly or as workers managed by Gunicorn:

TEXT
pip install uvicorn
uvicorn mysite.asgi:application --host 127.0.0.1 --port 8000 --workers 3

Do not expose these servers directly to the internet; put Nginx or a cloud load balancer in front. Keep the app server running with a process manager. On Linux that is usually systemd:

INI
# /etc/systemd/system/mysite.service (read-only)
[Unit]
Description=mysite gunicorn
After=network.target

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

[Install]
WantedBy=multi-user.target

Nginx as a reverse proxy

Nginx accepts the public connection, handles TLS certificates (often issued for free by Let's Encrypt with certbot), serves static files and passes everything else to Gunicorn:

NGINX
# /etc/nginx/sites-available/mysite (read-only)
server {
    listen 443 ssl;
    server_name example.com www.example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    client_max_body_size 10m;

    location /static/ {
        alias /srv/mysite/staticfiles/;
        expires 30d;
    }

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

The two proxy_set_header lines are what make ALLOWED_HOSTS and SECURE_PROXY_SSL_HEADER work correctly. User-uploaded media files usually go to object storage (S3-compatible) or get an extra location /media/ block; see Static Files and Media.

Static files with WhiteNoise

In development, runserver serves static files for you. In production Django does not. You have three options: let Nginx serve them (shown above), upload them to a CDN or object storage, or let the application serve them itself with WhiteNoise. WhiteNoise is popular on platforms where you cannot configure a web server, and with a CDN in front it performs very well.

First collect every app's static files into one folder, usually in the build step:

TEXT
python manage.py collectstatic --noinput

Then configure WhiteNoise:

Python
# settings.py (read-only)
STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",   # directly after SecurityMiddleware
    # ... the rest
]

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

The manifest storage gives each file a content hash in its name (app.3f9a1c.css) and compresses it. Because the name changes whenever the content changes, browsers and CDNs can cache files forever and still pick up new releases immediately.

Database configuration

Use a server database such as PostgreSQL in production. Connection details come from the environment, and two options deserve attention:

Python
# settings.py (read-only)
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["DB_HOST"],
        "PORT": os.environ.get("DB_PORT", "5432"),
        "CONN_MAX_AGE": 60,          # reuse connections for up to 60 s
        "CONN_HEALTH_CHECKS": True,  # drop a stale persistent connection instead of failing
    }
}

Each worker keeps its own connection, so the number of workers times the number of servers must stay below PostgreSQL's connection limit (a connection pooler such as PgBouncer helps at larger scale; Performance and Scaling returns to this). Run python manage.py migrate as a deliberate release step, not on every worker start, and prefer backward-compatible migrations (add columns first, remove them in a later release) so old and new code can run side by side during a rolling deploy.

Health checks

Load balancers, container orchestrators and uptime monitors need a URL they can ask "is this instance alive?". Provide two small endpoints: a liveness check that only proves the process responds, and a readiness check that also verifies dependencies like the database. Keep them cheap, unauthenticated and uncached. If you set SECURE_SSL_REDIRECT, exempt the path with SECURE_REDIRECT_EXEMPT when the platform probes over plain HTTP.

Python Liveness and readiness endpoints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When the database is unreachable the readiness endpoint answers 503, so the load balancer stops sending traffic to that instance while the liveness endpoint stays healthy, which prevents the orchestrator from restarting a process that merely lost its database for a moment.

Deploying to a PaaS host

A platform as a service (PaaS) runs the servers for you. You hand it your code and a few settings, and it builds the app, starts it behind a proxy with HTTPS, and restarts it if it crashes. It is the quickest way to put a project online and a sensible place to start. The details differ between providers, so use the following as a map and check your provider's current documentation for exact names and limits.

The Heroku-style workflow (Heroku, Render, Railway, Fly.io and similar)

These platforms share a pattern:

  1. Connect your Git repository (often GitHub) or git push to a remote the platform gives you. A push triggers a build.

  2. The platform detects Python from requirements.txt (or pyproject.toml) and installs your dependencies. Pin the Python version in the file your platform documents (for example .python-version or runtime.txt).

  3. A Procfile (or the platform's equivalent setting) names your processes. The web process is what receives traffic, and an optional release process runs once per deploy, which is the right place for migrations:

    TEXT
    # Procfile (read-only)
    release: python manage.py migrate --noinput
    web: gunicorn mysite.wsgi --log-file -
    
  4. Configuration is environment variables set on the platform: SECRET_KEY, DEBUG=false, ALLOWED_HOSTS and so on. A managed PostgreSQL add-on injects DATABASE_URL, which you parse with dj-database-url or django-environ, as covered above and in Database configuration. The platform also provides a PORT variable that Gunicorn uses by default, so you rarely set the bind address yourself.

  5. Static files go through WhiteNoise and collectstatic (a build step on most platforms), as described earlier in this lesson.

Four traits of these platforms catch beginners:

  • The file system is ephemeral. Anything written to disk at run time (uploads, a SQLite database file) vanishes on the next deploy or restart. Use the managed PostgreSQL for data and object storage such as S3 for user uploads (see Static Files and Media).
  • TLS is terminated by the platform's proxy, so your app sees plain HTTP. Tell Django to trust the proxy header: SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https"), otherwise request.is_secure() is false and redirects and CSRF checks misbehave.
  • Run one-off commands (createsuperuser, a data fix) through the platform's console or run command, not by editing the live server.
  • Scale by adding processes, not by hand-tuning one box. Several small web workers plus a separate worker process for background jobs (see Docker, Celery and CI) is the usual shape.

PythonAnywhere

PythonAnywhere is a PaaS aimed at beginners, and it works differently: there is no Procfile and no build pipeline. You work in a browser-based Bash console on the server itself:

  1. Get the code there: git clone your GitHub repository into your home folder (public repositories need no key).

  2. Create a virtualenv and install dependencies: mkvirtualenv --python=python3.13 myenv then pip install -r requirements.txt (use a Python version the platform offers).

  3. On the Web tab, add a web app with manual configuration, then fill in the source code path, the working directory and the virtualenv path.

  4. Edit the WSGI configuration file (a link on the Web tab). This file plays the part of wsgi.py; it puts your project on the path and names the settings module:

    Python
    # /var/www/yourusername_pythonanywhere_com_wsgi.py (read-only)
    import os
    import sys
    
    path = "/home/yourusername/mysite"
    if path not in sys.path:
        sys.path.insert(0, path)
    
    os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"
    os.environ["SECRET_KEY"] = "..."   # or load a .env file that is not in Git
    
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()
    
  5. Set ALLOWED_HOSTS = ["yourusername.pythonanywhere.com"], run python manage.py migrate and collectstatic in the console, and map the static URL (/static/) to your STATIC_ROOT folder in the Static files table on the Web tab, because the platform serves static files itself.

  6. Reload the web app (the green button) after every code or configuration change; to update later, git pull in the console and reload.

Free tiers have limits (for example, restricted outbound network access and no custom domain), so read the current plan details before choosing one for a real project.

What both have in common

Whatever the platform, the app must be reachable through a WSGI (or ASGI) module that exposes application; read its settings from the environment; refuse requests for unknown hosts; and keep data outside the code directory. The example below plays the platform's part: it writes a minimal project to the in-browser file system, reads the Procfile to find the module to import, boots the app with environment variables, and calls it the way Gunicorn would.

Python What a PaaS host does: read the Procfile, set the environment, call the WSGI app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The platform never runs your manage.py runserver. It imports mysite.wsgi, calls application for each request, and relies on your settings to do the rest. The request for an unknown host got 400 Bad Request because ALLOWED_HOSTS held only myapp.example.com, and the missing SECRET_KEY stopped the boot immediately instead of leaving a half-configured site running. That is exactly the behavior you want on a deploy: failures at start-up, visible in the platform's log, rather than quiet misbehavior later.

A final checklist before the first deploy: DEBUG is false, secrets and ALLOWED_HOSTS come from the environment, requirements.txt includes Gunicorn and WhiteNoise, migrations run in the release step, uploads go to object storage, SECURE_PROXY_SSL_HEADER is set behind the platform's proxy, and python manage.py check --deploy passes.

A release routine

Put the steps together and automate them (see Docker, Celery and CI):

  1. Build: install pinned dependencies and run collectstatic.
  2. Test: run the test suite and check --deploy.
  3. Migrate: apply database migrations.
  4. Switch: start the new app servers, wait for the readiness check, then stop the old ones.
  5. Watch: check error tracking and logs for new problems, with a rollback plan ready.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must DEBUG be False in production?

    With DEBUG on, Django shows detailed error pages including settings and code, which is a serious information leak. It also keeps every query in memory. Production must always run with DEBUG off.
  2. 2. What is ALLOWED_HOSTS for?

    When DEBUG is False Django accepts only the host names you list. This prevents host-header attacks, such as password-reset links pointing to an attacker's site.
  3. 3. Which approach is recommended for SECRET_KEY?

    Secrets belong in the environment or a secret store. Failing fast when it is missing avoids running with a guessable default, and a key regenerated on every start would break sessions across workers and restarts.
  4. 4. What does python manage.py collectstatic do?

    collectstatic gathers the static files of every installed app into the single STATIC_ROOT directory. In production, Nginx, a CDN or WhiteNoise serves them from there.
  5. 5. Why have a separate readiness check besides a liveness check?

    Liveness says the process responds. Readiness says it can do useful work (database reachable, caches warm). Orchestrators route traffic by readiness and restart by liveness.

Summary

  • Replace runserver with an application server (Gunicorn for WSGI, Uvicorn for ASGI) behind a reverse proxy such as Nginx that terminates HTTPS.
  • Production settings: DEBUG = False, a secret SECRET_KEY, a strict ALLOWED_HOSTS, HTTPS redirect, HSTS and secure cookies; verify them with check --deploy.
  • Keep configuration and secrets in environment variables, fail fast when a required one is missing, and never commit secrets.
  • Generate a unique SECRET_KEY per environment with get_random_secret_key(), load it with os.environ or django-environ, and rotate it with SECRET_KEY_FALLBACKS so users stay signed in.
  • On a PaaS host, the platform imports your WSGI module, reads configuration from environment variables, runs migrations in a release step and gives you an ephemeral file system; PythonAnywhere uses a WSGI configuration file and a Web tab instead of a Procfile.
  • Run collectstatic at build time and serve static files with Nginx, a CDN or WhiteNoise's hashed, compressed storage.
  • Use PostgreSQL with persistent connections, run migrations as a release step, and write backward-compatible migrations.
  • Add cheap liveness and readiness endpoints so load balancers know when to send traffic.

Next lesson: Docker, Celery and CI for Django.