← Back to Django, page 5

django-0095 · Hard senior

How do you containerise a Django app for production: Dockerfile, Gunicorn, static files with WhiteNoise, migrations and health checks?

Build a slim multi-stage image that installs pinned dependencies, runs as a non-root user, collects static files at build time, and starts Gunicorn (or Uvicorn workers) with settings read from environment variables. WhiteNoise serves hashed, compressed static files directly from the app container so a CDN or proxy can cache them. Run migrations as a separate release step rather than on every container start, expose a health endpoint, and log to stdout.

Full answer

A reasonable image:

dockerfile
FROM python:3.13-slim AS build
ENV PIP_NO_CACHE_DIR=1 PYTHONDONTWRITEBYTECODE=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --prefix=/install -r requirements.txt

FROM python:3.13-slim
ENV PYTHONUNBUFFERED=1 DJANGO_SETTINGS_MODULE=proj.settings
RUN useradd --create-home app
WORKDIR /app
COPY --from=build /install /usr/local
COPY . .
RUN SECRET_KEY=build-only python manage.py collectstatic --noinput
USER app
EXPOSE 8000
CMD ["gunicorn", "proj.wsgi", "--bind", "0.0.0.0:8000", "--workers", "3", "--access-logfile", "-"]

Decisions:

  • Pin dependencies with hashes or a lock file, use a slim base image, no build tools in the final stage, and a non-root user.
  • Configuration comes from environment variables (SECRET_KEY, DATABASE_URL, ALLOWED_HOSTS, CSRF_TRUSTED_ORIGINS). Never bake secrets into the image; the collectstatic build step needs a dummy key only.
  • Static files: STORAGES["staticfiles"]["BACKEND"] = "whitenoise.storage.CompressedManifestStaticFilesStorage" gives content-hashed names (app.3f2a1b9c.css), gzip or Brotli copies and Cache-Control: max-age=315360000, public, immutable (ten years, safe because the name changes with the content). Add WhiteNoiseMiddleware right after SecurityMiddleware. Put a CDN in front for traffic. User uploads (media) belong in object storage, not the container filesystem.
  • Workers: Gunicorn --workers around 2 to 4 per CPU core for sync workers; for ASGI use gunicorn -k uvicorn.workers.UvicornWorker (or uvicorn --workers). Set --timeout, --max-requests with jitter to recycle leaky processes, and --graceful-timeout.
  • Reverse proxy: SECURE_PROXY_SSL_HEADER, USE_X_FORWARDED_HOST only if the proxy sets them, and --forwarded-allow-ips.
  • Migrations: run python manage.py migrate as a release job (init container or pipeline step) before the new version takes traffic; keep migrations backward-compatible so old and new pods can overlap.
  • Health: /healthz/ returns 200 without touching the database (liveness); readiness may check the database.
  • Logs to stdout in a structured format; one process per container.
python
import re
import sys
import tempfile
import types
from pathlib import Path

WORK = Path(tempfile.mkdtemp())
(WORK / "assets").mkdir()
(WORK / "assets" / "app.css").write_text("body { font-family: sans-serif; }\n" * 50)

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    ROOT_URLCONF=__name__,
    DEBUG=False,
    STATIC_URL="/static/",
    STATIC_ROOT=str(WORK / "staticfiles"),
    STATICFILES_DIRS=[str(WORK / "assets")],
    STORAGES={"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
              "staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"}},
    MIDDLEWARE=["django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware"],
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "django.contrib.staticfiles", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import io

from django.core.management import call_command
from django.http import HttpResponse
from django.templatetags.static import static
from django.test import Client
from django.urls import path


def healthz(request):
    return HttpResponse("ok")                         # liveness: no database access


urlpatterns = [path("healthz/", healthz)]

call_command("collectstatic", interactive=False, verbosity=0)
names = sorted(p.name for p in (WORK / "staticfiles").iterdir())
mask = lambda name: re.sub(r"\.[0-9a-f]{12}\.", ".<hash>.", name)
print([mask(n) for n in names])

url = static("app.css")
print(mask(url))
c = Client()
r = c.get(url, headers={"Accept-Encoding": "gzip"})
print(r.status_code, r.headers.get("Content-Encoding"), r.headers.get("Cache-Control"))
print(c.get("/healthz/").content)

Standalone script. Needs `pip install whitenoise`. It builds a temporary static directory, runs collectstatic with the manifest storage and fetches a file through WhiteNoise. The Dockerfile and Gunicorn command are shown in the answer text, not executed here. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['app.<hash>.css', 'app.<hash>.css.gz', 'app.css', 'app.css.gz', 'staticfiles.json'] /static/app.<hash>.css 200 gzip max-age=315360000, public, immutable b'ok'

Key points

  • Multi-stage, slim, non-root image with pinned dependencies
  • Configuration through environment variables; no secrets in images
  • WhiteNoise serves hashed, compressed static files with long cache lifetimes
  • Run migrations as a separate release step
  • Gunicorn worker count, timeouts and recycling; health endpoints; stdout logs

Common mistakes

  • Running migrate automatically in every container at start-up
  • Baking secrets or .env files into the image
  • Serving media uploads from the container filesystem
  • Running as root in the container
  • Setting Gunicorn workers without considering memory and database connections

Follow-ups

  • How would you roll out a breaking migration with zero downtime?
  • How do you size Gunicorn workers and database connections together?
  • How do liveness and readiness probes differ?

Tips

  • Walk through the Dockerfile stages
  • Mention WhiteNoise and hashed names
  • Say migrations as a release step