ZetCode

Docker and Django

last modified November 22, 2026 Python 3.15

Docker packs an application with everything it needs to run, the operating system libraries, the Python interpreter, and the installed packages, into an image. A container started from the image behaves the same on the laptop of a developer, on a build server, and in production. In this article we build an image of a small Django project with uv, run it with Gunicorn, and then run it together with a PostgreSQL database in Docker Compose, with migrations, a volume for the data, and health checks. The examples use Django 6.1, Gunicorn 27, WhiteNoise 6.12, PostgreSQL 18, Docker 29 with Compose 5, and Python 3.15.

The basics of Docker images and containers are explained in Python Docker. Running Django on a server without containers, with systemd and Nginx, is the topic of Django deployment; here we reuse its settings and let Docker take the role of the service manager.

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 books.

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

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',
    'books',
]

uv records the packages in pyproject.toml and their exact versions, including the dependencies of dependencies, in uv.lock. The image is built from these two files, so it contains the same versions as the development machine.

Settings from the environment

An image should not contain secrets or settings that differ between machines; the same image runs in development, testing, and production, and each environment passes its own values to the container as 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. ALLOWED_HOSTS is a comma-separated list with localhost as the default. These settings are explained in Django settings and environment. For the development machine, we put the values into the file .env.

.env
DJANGO_SECRET_KEY=local-key-for-development-only-7c1e9a3f5d2b4e6a8f0d
DJANGO_DEBUG=1

uv loads a file of variables for every uv run command when the environment variable UV_ENV_FILE names it. We export it once in the shell; all later uv run commands on the development machine get the secret key and debugging on.

$ export UV_ENV_FILE=.env
$ uv run python manage.py check
System check identified no issues (0 silenced).

Static files and logging

A container runs one process, Gunicorn, so the static files are served by the Django application with WhiteNoise. 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',
]

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 gives every file a copy with a hash of its content in the name, and the static tag writes the hashed name into the page, so browsers can keep the files in their cache forever. WhiteNoise and the storage are described in more detail in Django deployment. The last addition is a logging configuration at the end of the settings file.

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

Docker collects what a container writes to its standard output and standard error streams; the command docker logs shows it. By default Django prints errors to the console only when DEBUG is on. This configuration prints warnings and errors of all loggers to the standard error stream also in production, so we see the tracebacks of failed requests in the container log.

The books app

The application shows a list of books. The model has the title, the author, and the year of publication.

books/models.py
from django.db import models


class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    published = models.PositiveSmallIntegerField()

    class Meta:
        ordering = ['published']

    def __str__(self):
        return self.title

The books come from a fixture, a JSON file in the app's fixtures directory, which we can load into any database with loaddata.

books/fixtures/books.json
[
  {"model": "books.book", "pk": 1,
   "fields": {"title": "The C Programming Language", "author": "Kernighan, Ritchie",
              "published": 1978}},
  {"model": "books.book", "pk": 2,
   "fields": {"title": "Refactoring", "author": "Martin Fowler", "published": 1999}},
  {"model": "books.book", "pk": 3,
   "fields": {"title": "Fluent Python", "author": "Luciano Ramalho", "published": 2015}}
]

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

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

The views

The home page lists the books and shows the host name of the machine that rendered it; in a container, the host name is the short id of the container. The health view checks that the database connection works and returns a JSON status, 503 Service Unavailable on failure. We use it later in a health check.

books/views.py
import socket

from django.db import connection
from django.http import JsonResponse
from django.shortcuts import render

from .models import Book


def home(request):
    books = Book.objects.all()
    return render(request, 'books/home.html',
                  {'books': books, 'host': socket.gethostname()})


def health(request):
    try:
        connection.ensure_connection()
    except Exception as e:
        return JsonResponse({'status': 'error', 'error': str(e)}, status=503)
    return JsonResponse({'status': 'ok', 'database': connection.vendor})

ensure_connection() opens the database connection if it is not open yet, and raises an exception when the database is unreachable. The app's URLconf maps the two views.

books/urls.py
from django.urls import path

from . import views

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

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('books.urls')),
]

The template links a stylesheet with the static tag and prints the books and the host name.

books/templates/books/home.html
{% load static %}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Bookshelf</title>
  <link rel="stylesheet" href="{% static 'books/style.css' %}">
</head>
<body>
  <h1>Bookshelf</h1>
  <ul>
  {% for book in books %}
    <li>{{ book.title }} by {{ book.author }}, {{ book.published }}</li>
  {% endfor %}
  </ul>
  <footer>Served by {{ host }}</footer>
</body>
</html>

The stylesheet is a static file of the app.

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

footer {
  color: #666;
}

We start the development server with uv run python manage.py runserver and ask for the two pages in another terminal. The footer shows the host name of the development machine.

$ curl -s localhost:8000/ | grep -E '<li>|<footer'
    <li>The C Programming Language by Kernighan, Ritchie, 1978</li>
    <li>Refactoring by Martin Fowler, 1999</li>
    <li>Fluent Python by Luciano Ramalho, 2015</li>
  <footer>Served by universum</footer>
$ curl -s localhost:8000/health/
{"status": "ok", "database": "sqlite"}

A first Dockerfile

A Dockerfile in the project directory describes how to build the image. Each instruction adds a layer to the image, starting from a base image.

Dockerfile
FROM python:3.15-slim

COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /bin/uv

WORKDIR /app
COPY . .
RUN uv sync --frozen --no-dev

ENV PATH="/app/.venv/bin:$PATH"

CMD ["gunicorn", "config.wsgi"]

The base image python:3.15-slim is Debian with Python 3.15 and only the most necessary system packages. COPY --from copies the uv binary out of the official uv image; we pin its version, so that a rebuild next year gives the same tool. WORKDIR creates the directory /app and makes it the current directory of the following instructions and of the container. COPY . . copies the project directory into it, and uv sync creates the virtual environment .venv from the lock file. --frozen uses the lock file as it is, without checking it against pyproject.toml, and --no-dev leaves out development dependencies.

ENV PATH puts the binaries of the virtual environment first in the search path, so python and gunicorn are the ones from .venv, without uv run. CMD is the command of the container. We write it in the exec form, a JSON list, so Gunicorn runs as the main process of the container and receives the stop signal from Docker; the shell form would start it under /bin/sh. We build the image with the name bookshelf; the dot is the build context, the directory whose files the build can copy.

The output is shortened to the size of the build context and the steps of the Dockerfile. The context has more than 30 MB for a project of a few small files, and uv warns about an existing virtual environment that it removes: COPY . . copied the .venv directory of the development machine, which is useless in the image because it links to the Python interpreter of the host. uv uses the system Python of the image, which is 3.15.2.

$ docker build -t bookshelf .
#7 [internal] load build context
#7 transferring context: 31.62MB 0.4s done
#6 [stage-0 1/5] FROM docker.io/library/python:3.15-slim
#6 CACHED
#8 [stage-0 2/5] COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /bin/uv
#8 DONE 0.1s
#9 [stage-0 3/5] WORKDIR /app
#9 DONE 0.1s
#10 [stage-0 4/5] COPY . .
#10 DONE 0.5s
#11 [stage-0 5/5] RUN uv sync --frozen --no-dev
#11 0.183 warning: Ignoring existing virtual environment linked to non-existent Python interpreter: `.venv/bin/python` -> `/home/user/.local/share/uv/python/cpython-3.15/bin/python3.15`
#11 0.344 Using CPython 3.15.2 interpreter at: /usr/local/bin/python3
#11 0.597 Removed virtual environment at: .venv
#11 0.597 Creating virtual environment at: .venv
#11 3.780 Installed 5 packages in 105ms
#11 3.780  + asgiref==3.13.0
#11 3.780  + django==6.1.3
#11 3.780  + gunicorn==27.0.1
#11 3.780  + sqlparse==0.6.1
#11 3.780  + whitenoise==6.12.0
#11 DONE 3.9s
$ docker images --format 'table {{.Repository}}\t{{.Tag}}\t{{.Size}}' bookshelf
REPOSITORY   TAG       SIZE
bookshelf    latest    221MB

What got into the image

The docker run command starts a container from the image; an argument after the image name replaces the CMD. The option --rm removes the container when the command ends. We list the files in /app and print .env.

Next to the useless virtual environment, the image contains the local SQLite database and the .env file with the secret key. Anybody who can pull the image can read them. An image is often pushed to a registry and shared, so it must not contain secrets.

$ docker run --rm bookshelf ls -A
.env
.venv
Dockerfile
books
config
db.sqlite3
manage.py
pyproject.toml
uv.lock
$ docker run --rm bookshelf cat .env
DJANGO_SECRET_KEY=local-key-for-development-only-7c1e9a3f5d2b4e6a8f0d
DJANGO_DEBUG=1

The .dockerignore file

The file .dockerignore in the build context lists the files that Docker does not send to the builder. The patterns work like those of .gitignore.

.dockerignore
.env
.git
.venv
__pycache__
db.sqlite3
staticfiles

We exclude the local secrets, the Git repository, the virtual environment, the Python bytecode cache, the local database, and the collected static files. We rebuild the image with the same command.

The build context now has 2 kB, the image no longer contains .env, and it is smaller, because the copied virtual environment was in the layer of COPY even though uv removed it in the next layer: a later layer can hide a file, but not make an earlier layer smaller.

$ docker build -t bookshelf .
#7 [internal] load build context
#7 transferring context: 2.00kB 0.1s done
#6 [stage-0 1/5] FROM docker.io/library/python:3.15-slim
#6 DONE 0.0s
#8 [stage-0 2/5] COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /bin/uv
#8 CACHED
#9 [stage-0 3/5] WORKDIR /app
#9 CACHED
#10 [stage-0 4/5] COPY . .
#10 DONE 0.1s
#11 [stage-0 5/5] RUN uv sync --frozen --no-dev
#11 DONE 3.7s
$ docker run --rm bookshelf ls -A
.dockerignore
.venv
Dockerfile
books
config
manage.py
pyproject.toml
uv.lock
$ docker images --format 'table {{.Repository}}\t{{.Tag}}\t{{.Size}}' bookshelf
REPOSITORY   TAG       SIZE
bookshelf    latest    190MB

Running the container

We start a container in the background with -d and give it the name web. The option -p 8000:8000 publishes the port 8000 of the container on the port 8000 of the host, and -e sets the secret key. DJANGO_DEBUG is not set, so the project runs in production mode. The command prints the id of the new container.

The request fails with a reset connection. The log shows why: Gunicorn listens on 127.0.0.1, its default. A container has its own network interfaces, and its loopback address is reachable only from inside the container; Docker forwards the published port to the container's external interface. WhiteNoise warns that the directory of collected static files does not exist; we come to it soon.

$ docker run -d --name web -p 8000:8000 -e DJANGO_SECRET_KEY=container-key-2b8e4f6a1c3d5e7f9a0b bookshelf
dd66e872b64b002c82ccfe002b920b7846b32bea129b3cadb1fa0f150a9f0e12
$ curl -sS localhost:8000/
curl: (56) Recv failure: Connection reset by peer
$ docker logs web
[2026-11-22 20:53:57 +0000] [1] [INFO] Starting gunicorn 27.0.1
[2026-11-22 20:53:57 +0000] [1] [INFO] Listening at: http://127.0.0.1:8000 (1)
[2026-11-22 20:53:57 +0000] [1] [INFO] Using worker: sync
[2026-11-22 20:53:57 +0000] [7] [INFO] Booting worker with pid: 7
[2026-11-22 20:53:57 +0000] [1] [INFO] Control socket listening at /root/.gunicorn/gunicorn.ctl

The Gunicorn configuration file

Gunicorn reads its settings from the file gunicorn.conf.py in the current directory, which in the container is /app. We create the file in the project directory.

gunicorn.conf.py
bind = '0.0.0.0:8000'
workers = 2
accesslog = '-'

0.0.0.0 means all interfaces of the container. It does not expose the server to the world; only the ports published with -p are reachable from outside the container. workers is the number of worker processes, and accesslog = '-' writes a line for each request to the standard output, which goes to the container log. We remove the old container with docker rm -f web, rebuild the image, and start a new container; the build output is left out.

The health endpoint answers, but the home page gives 500. The log is shortened: the traceback of the error is replaced with three dots.

$ docker rm -f web
web
$ docker build -t bookshelf .
$ docker run -d --name web -p 8000:8000 -e DJANGO_SECRET_KEY=container-key-2b8e4f6a1c3d5e7f9a0b bookshelf
4af3f74d3413006602a3c59fe1f995ced2deabfb10e7bf2aac5748fe3575b916
$ curl -s localhost:8000/health/
{"status": "ok", "database": "sqlite"}
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/
500
$ docker logs web
[2026-11-22 20:54:03 +0000] [1] [INFO] Starting gunicorn 27.0.1
[2026-11-22 20:54:03 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2026-11-22 20:54:03 +0000] [1] [INFO] Using worker: sync
[2026-11-22 20:54:03 +0000] [7] [INFO] Booting worker with pid: 7
[2026-11-22 20:54:03 +0000] [8] [INFO] Booting worker with pid: 8
[2026-11-22 20:54:03 +0000] [1] [INFO] Control socket listening at /root/.gunicorn/gunicorn.ctl
/app/.venv/lib/python3.15/site-packages/django/core/handlers/base.py:63: UserWarning: No directory at: /app/staticfiles/
  mw_instance = middleware(adapted_handler)
172.17.0.1 - - [22/Nov/2026:20:54:04 +0000] "GET /health/ HTTP/1.1" 200 38 "-" "curl/7.81.0"
Internal Server Error: /
...
ValueError: Missing staticfiles manifest entry for 'books/style.css'
172.17.0.1 - - [22/Nov/2026:20:54:04 +0000] "GET / HTTP/1.1" 500 145 "-" "curl/7.81.0"

Collecting static files in the image

The static tag looks up the hashed name of the stylesheet in the manifest, a file that collectstatic writes into STATIC_ROOT. The directory is not in the image, so the lookup fails. The static files are part of the code, so we collect them when we build the image. We add a RUN instruction after ENV PATH.

Dockerfile
FROM python:3.15-slim

COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /bin/uv

WORKDIR /app
COPY . .
RUN uv sync --frozen --no-dev

ENV PATH="/app/.venv/bin:$PATH"
RUN DJANGO_SECRET_KEY=build-only python manage.py collectstatic --noinput

CMD ["gunicorn", "config.wsgi"]

The settings need a secret key even for collectstatic, which does not use it. We set a dummy value only for this one command; it is not stored in the image as an ENV instruction would be. The output of the build is shortened to the new step. We start a container from the new image and ask for the home page again.

The page still fails, now with a database error: the SQLite database in the image has no tables, because we excluded db.sqlite3 and never ran the migrations in the container.

$ docker rm -f web
web
$ docker build -t bookshelf .
#12 [stage-0 6/6] RUN DJANGO_SECRET_KEY=build-only python manage.py collectstatic --noinput
#12 1.572 131 static files copied to '/app/staticfiles', 391 post-processed.
#12 DONE 1.7s
$ docker run -d --name web -p 8000:8000 -e DJANGO_SECRET_KEY=container-key-2b8e4f6a1c3d5e7f9a0b bookshelf
98305ca3429530372da168d8d380528893c0c89af693fb358489b99263bd9a2e
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/
500
$ docker logs web
[2026-11-22 20:54:12 +0000] [1] [INFO] Starting gunicorn 27.0.1
[2026-11-22 20:54:12 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2026-11-22 20:54:12 +0000] [1] [INFO] Using worker: sync
[2026-11-22 20:54:12 +0000] [7] [INFO] Booting worker with pid: 7
[2026-11-22 20:54:12 +0000] [8] [INFO] Booting worker with pid: 8
[2026-11-22 20:54:12 +0000] [1] [INFO] Control socket listening at /root/.gunicorn/gunicorn.ctl
Internal Server Error: /
...
django.db.utils.OperationalError: no such table: books_book
172.17.0.1 - - [22/Nov/2026:20:54:12 +0000] "GET / HTTP/1.1" 500 145 "-" "curl/7.81.0"

Management commands in a container

docker exec runs a command in a running container, with the same environment variables and working directory as the main process. We apply the migrations and load the fixture; the output of migrate is shortened.

The page works. The stylesheet has the hashed name, and WhiteNoise serves it with a cache time of ten years. The footer shows the host name of the container, which is the beginning of its id, as docker ps confirms.

$ docker exec web python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, books, contenttypes, sessions
Running migrations:
  Applying books.0001_initial... OK
$ docker exec web python manage.py loaddata books
Installed 3 object(s) from 1 fixture(s)
$ curl -s localhost:8000/ | grep -E 'stylesheet|<li>|<footer'
  <link rel="stylesheet" href="/static/books/style.66d7ffff0463.css">
    <li>The C Programming Language by Kernighan, Ritchie, 1978</li>
    <li>Refactoring by Martin Fowler, 1999</li>
    <li>Fluent Python by Luciano Ramalho, 2015</li>
  <footer>Served by 98305ca34295</footer>
$ CSS=$(curl -s localhost:8000/ | grep -o '/static/books/style[^"]*')
$ curl -sI localhost:8000$CSS | grep -iE '^(HTTP|cache-control)'
HTTP/1.1 200 OK
Cache-Control: max-age=315360000, public, immutable
$ docker ps --format "{{.ID}} {{.Names}} {{.Status}}"
98305ca34295 web Up 2 seconds

Containers are disposable

The database file was written into the container's own writable layer, on top of the image. When we remove the container and start a new one from the same image, the new container starts with the files of the image.

The tables and the books are gone. A container should be replaceable at any time, for example by a new version of the image, so data must live outside it: in a database server or in a volume. We use both in the second part of the article. We remove the container; it is not needed anymore.

$ docker rm -f web
web
$ docker run -d --name web -p 8000:8000 -e DJANGO_SECRET_KEY=container-key-2b8e4f6a1c3d5e7f9a0b bookshelf
baa1ee66cea66a4faf3dfcfa37da6f316f0f96412d45eb937c2f900fcbbc05d6
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/
500
$ docker logs web | grep OperationalError
sqlite3.OperationalError: no such table: books_book
django.db.utils.OperationalError: no such table: books_book
$ docker rm -f web
web

Rebuilding after a code change

During development we change the code often. We change the heading in the template to My bookshelf and build the image again. The output is shortened to the steps.

Docker reuses a cached layer only if the instruction and everything before it are unchanged; for COPY, the copied files must be the same too. A change of any file in the project changes the layer of COPY . ., so every later step runs again, and uv downloads and installs all the packages for a one-line change in a template.

$ docker build -t bookshelf .
#6 [stage-0 1/6] FROM docker.io/library/python:3.15-slim
#6 DONE 0.0s
#8 [stage-0 2/6] COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /bin/uv
#8 CACHED
#9 [stage-0 3/6] WORKDIR /app
#9 CACHED
#10 [stage-0 4/6] COPY . .
#10 DONE 0.0s
#11 [stage-0 5/6] RUN uv sync --frozen --no-dev
#11 0.511 Downloading django (8.0MiB)
#11 3.800 Installed 5 packages in 102ms
#11 DONE 3.9s
#12 [stage-0 6/6] RUN DJANGO_SECRET_KEY=build-only python manage.py collectstatic --noinput
#12 DONE 1.7s

Layer caching

The packages depend only on pyproject.toml and uv.lock. We copy these two files first, install the packages, and copy the rest of the project afterwards.

Dockerfile
FROM python:3.15-slim

COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /bin/uv

WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev

COPY . .

ENV PATH="/app/.venv/bin:$PATH"
RUN DJANGO_SECRET_KEY=build-only python manage.py collectstatic --noinput

CMD ["gunicorn", "config.wsgi"]

uv needs only the two files, because the project itself is not a package that is installed into the virtual environment. The first build with the new Dockerfile installs the packages once more. Then we change the heading back to Bookshelf and build again.

All steps up to uv sync come from the cache; only the copy of the project and collectstatic run again. The packages are installed again only when the lock file changes.

$ docker build -t bookshelf .
#6 [stage-0 1/7] FROM docker.io/library/python:3.15-slim
#6 DONE 0.0s
#8 [stage-0 2/7] COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /bin/uv
#8 CACHED
#9 [stage-0 3/7] WORKDIR /app
#9 CACHED
#10 [stage-0 4/7] COPY pyproject.toml uv.lock ./
#10 CACHED
#11 [stage-0 5/7] RUN uv sync --frozen --no-dev
#11 CACHED
#12 [stage-0 6/7] COPY . .
#12 DONE 0.0s
#13 [stage-0 7/7] RUN DJANGO_SECRET_KEY=build-only python manage.py collectstatic --noinput
#13 DONE 1.7s

PostgreSQL

In the second part of the article, the data lives in a PostgreSQL server, which runs in a container next to the application. Django talks to PostgreSQL through the driver psycopg; the binary extra installs a build with the C library included, so the slim image needs no compiler and no system packages.

$ uv add 'psycopg[binary]'
Resolved 9 packages in 2ms
Installed 2 packages in 1ms
 + psycopg==3.3.9
 + psycopg-binary==3.3.9

Database settings

The database settings come from the environment as well. We keep the generated SQLite configuration for the development machine and replace it when the variable POSTGRES_HOST is set. The code goes after the generated DATABASES in config/settings.py.

config/settings.py
if os.environ.get('POSTGRES_HOST'):
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'HOST': os.environ['POSTGRES_HOST'],
            'NAME': os.environ['POSTGRES_DB'],
            'USER': os.environ['POSTGRES_USER'],
            'PASSWORD': os.environ['POSTGRES_PASSWORD'],
        }
    }

We also add the password of the database user to .env. Docker Compose reads the file too, as we see in the next section.

.env
DJANGO_SECRET_KEY=local-key-for-development-only-7c1e9a3f5d2b4e6a8f0d
DJANGO_DEBUG=1
POSTGRES_PASSWORD=bookshelf-db-secret-5e2a

POSTGRES_HOST is not in the file, so the development machine still uses SQLite.

$ uv run python manage.py shell --no-imports -c "from django.db import connection; print(connection.vendor)"
sqlite

Docker Compose

Docker Compose starts several containers that belong together from one file, compose.yaml. Each service is a container, and Compose creates a network in which the containers reach each other by the service names.

compose.yaml
services:
  db:
    image: postgres:18
    environment:
      POSTGRES_DB: bookshelf
      POSTGRES_USER: bookshelf
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - pgdata:/var/lib/postgresql

  web:
    build: .
    ports:
      - "8000:8000"
    environment:
      DJANGO_SECRET_KEY: ${DJANGO_SECRET_KEY}
      POSTGRES_HOST: db
      POSTGRES_DB: bookshelf
      POSTGRES_USER: bookshelf
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    depends_on:
      - db

volumes:
  pgdata:

The service db runs the official PostgreSQL image. On the first start, the image creates the database and the user from the variables POSTGRES_DB, POSTGRES_USER, and POSTGRES_PASSWORD. The named volume pgdata keeps the data directory; images of PostgreSQL 18 store the data in a subdirectory of /var/lib/postgresql, so we mount the volume there.

The service web is built from the Dockerfile in the current directory. Its environment points Django to the host db, which is the name of the database service. The ${...} expressions are replaced with values from the shell or from the file .env next to compose.yaml, which Compose reads automatically; the secrets stay out of the file, which belongs to the repository. Only the variables listed in environment get into the container, so DJANGO_DEBUG=1 from .env does not. depends_on starts the database container before the web container. The database port is not published, so PostgreSQL is reachable only from the containers of the project.

We start the project with docker compose up -d. --build builds the image first; the build output is left out. Compose names the image, the network, the volume, and the containers after the project directory.

$ docker compose up -d --build
 Image bookshelf-web Building 
 Image bookshelf-web Built 
 Network bookshelf_default Creating 
 Volume bookshelf_pgdata Creating 
 Volume bookshelf_pgdata Created 
 Network bookshelf_default Created 
 Container bookshelf-db-1 Creating 
 Container bookshelf-db-1 Created 
 Container bookshelf-web-1 Creating 
 Container bookshelf-web-1 Created 
 Container bookshelf-db-1 Starting 
 Container bookshelf-db-1 Started 
 Container bookshelf-web-1 Starting 
 Container bookshelf-web-1 Started 
$ docker compose ps --format "table {{.Name}}\t{{.Service}}\t{{.Status}}\t{{.Ports}}"
NAME              SERVICE   STATUS         PORTS
bookshelf-db-1    db        Up 2 seconds   5432/tcp
bookshelf-web-1   web       Up 2 seconds   0.0.0.0:8000->8000/tcp, [::]:8000->8000/tcp

Migrations with Compose

The health endpoint reports a working connection to PostgreSQL, but the home page fails: the new database is empty. docker compose logs prints the logs of a service, each line with the name of the container.

docker compose exec runs a command in the container of a service, like docker exec. We apply the migrations, load the fixture, and look at the table with psql in the database container. The output of migrate is shortened.

$ curl -s localhost:8000/health/
{"status": "ok", "database": "postgresql"}
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/
500
$ docker compose logs web | grep Error
web-1  | Internal Server Error: /
web-1  | django.db.utils.ProgrammingError: relation "books_book" does not exist
$ docker compose exec web python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, books, contenttypes, sessions
Running migrations:
  Applying books.0001_initial... OK
$ docker compose exec web python manage.py loaddata books
Installed 3 object(s) from 1 fixture(s)
$ curl -s localhost:8000/ | grep -E '<li>|<footer'
    <li>The C Programming Language by Kernighan, Ritchie, 1978</li>
    <li>Refactoring by Martin Fowler, 1999</li>
    <li>Fluent Python by Luciano Ramalho, 2015</li>
  <footer>Served by e65aa7a4ad0c</footer>
$ docker compose exec db psql -U bookshelf -c "select title, published from books_book"
           title            | published 
----------------------------+-----------
 The C Programming Language |      1978
 Refactoring                |      1999
 Fluent Python              |      2015
(3 rows)

Volumes

docker compose down stops and removes the containers and the network, but keeps the named volume. When we start the project again, the new database container finds the data directory in the volume, and the books are still there.

docker compose down -v removes the volumes too, and with them the data. We use it here to start over with an empty database.

$ docker compose down
 Container bookshelf-web-1 Stopping 
 Container bookshelf-web-1 Stopped 
 Container bookshelf-web-1 Removing 
 Container bookshelf-web-1 Removed 
 Container bookshelf-db-1 Stopping 
 Container bookshelf-db-1 Stopped 
 Container bookshelf-db-1 Removing 
 Container bookshelf-db-1 Removed 
 Network bookshelf_default Removing 
 Network bookshelf_default Removed 
$ docker volume ls --filter name=bookshelf
DRIVER    VOLUME NAME
local     bookshelf_pgdata
$ docker compose up -d
 Network bookshelf_default Creating 
 Network bookshelf_default Created 
 Container bookshelf-db-1 Creating 
 Container bookshelf-db-1 Created 
 Container bookshelf-web-1 Creating 
 Container bookshelf-web-1 Created 
 Container bookshelf-db-1 Starting 
 Container bookshelf-db-1 Started 
 Container bookshelf-web-1 Starting 
 Container bookshelf-web-1 Started 
$ curl -s localhost:8000/ | grep -c '<li>'
3
$ docker compose down -v
 Container bookshelf-web-1 Stopping 
 Container bookshelf-web-1 Stopped 
 Container bookshelf-web-1 Removing 
 Container bookshelf-web-1 Removed 
 Container bookshelf-db-1 Stopping 
 Container bookshelf-db-1 Stopped 
 Container bookshelf-db-1 Removing 
 Container bookshelf-db-1 Removed 
 Volume bookshelf_pgdata Removing 
 Network bookshelf_default Removing 
 Volume bookshelf_pgdata Removed 
 Network bookshelf_default Removed

Waiting for the database

depends_on waits only until the database container has started, not until PostgreSQL accepts connections. On the first start with an empty volume, the image initializes the database with a temporary server and restarts it, which takes a few seconds. We start the project and run the migrations right away.

The migrations fail, because PostgreSQL is not ready yet. A started container is not a ready service.

$ docker compose up -d
 Network bookshelf_default Creating 
 Volume bookshelf_pgdata Creating 
 Volume bookshelf_pgdata Created 
 Network bookshelf_default Created 
 Container bookshelf-db-1 Creating 
 Container bookshelf-db-1 Created 
 Container bookshelf-web-1 Creating 
 Container bookshelf-web-1 Created 
 Container bookshelf-db-1 Starting 
 Container bookshelf-db-1 Started 
 Container bookshelf-web-1 Starting 
 Container bookshelf-web-1 Started 
$ docker compose exec web python manage.py migrate | tail -n 3
    raise last_ex.with_traceback(None)
django.db.utils.OperationalError: connection failed: connection to server at "172.19.0.2", port 5432 failed: Connection refused
	Is the server running on that host and accepting TCP/IP connections?

A health check of the database

A health check is a command that Docker runs in the container at an interval; the exit code 0 means healthy. We add one to the db service and make web wait for the healthy state. The new lines are the healthcheck of db and the long form of depends_on.

compose.yaml
services:
  db:
    image: postgres:18
    environment:
      POSTGRES_DB: bookshelf
      POSTGRES_USER: bookshelf
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - pgdata:/var/lib/postgresql
    healthcheck:
      test: ["CMD", "pg_isready", "-h", "localhost", "-U", "bookshelf", "-d", "bookshelf"]
      interval: 2s
      timeout: 5s
      retries: 15

  web:
    build: .
    ports:
      - "8000:8000"
    environment:
      DJANGO_SECRET_KEY: ${DJANGO_SECRET_KEY}
      POSTGRES_HOST: db
      POSTGRES_DB: bookshelf
      POSTGRES_USER: bookshelf
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    depends_on:
      db:
        condition: service_healthy

volumes:
  pgdata:

pg_isready comes with PostgreSQL and checks that the server accepts connections. We give it -h localhost to check the TCP port: the temporary server used during the initialization listens only on a Unix socket, so a check over the socket could report a server that is about to be stopped. The check runs every two seconds; after 15 failed attempts the container is marked unhealthy. The condition service_healthy starts web only when the check of db succeeds.

Compose now waits for the database, and the migrations run without an error.

$ docker compose up -d
 Network bookshelf_default Creating 
 Volume bookshelf_pgdata Creating 
 Volume bookshelf_pgdata Created 
 Network bookshelf_default Created 
 Container bookshelf-db-1 Creating 
 Container bookshelf-db-1 Created 
 Container bookshelf-web-1 Creating 
 Container bookshelf-web-1 Created 
 Container bookshelf-db-1 Starting 
 Container bookshelf-db-1 Started 
 Container bookshelf-db-1 Waiting 
 Container bookshelf-db-1 Healthy 
 Container bookshelf-web-1 Starting 
 Container bookshelf-web-1 Started 
$ docker compose exec web python manage.py migrate | tail -n 2
  Applying books.0001_initial... OK
  Applying sessions.0001_initial... OK
$ docker compose ps --format "table {{.Service}}\t{{.Status}}"
SERVICE   STATUS
db        Up 3 seconds (healthy)
web       Up 1 second

A migration service

Running the migrations by hand is easy to forget. A common solution is a separate service that runs migrate and exits. Both Django services use the same image and environment, so we move the common part into an extension field and merge it into the services with a YAML anchor.

compose.yaml
x-django: &django
  build: .
  image: bookshelf
  environment:
    DJANGO_SECRET_KEY: ${DJANGO_SECRET_KEY}
    POSTGRES_HOST: db
    POSTGRES_DB: bookshelf
    POSTGRES_USER: bookshelf
    POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}

services:
  db:
    image: postgres:18
    environment:
      POSTGRES_DB: bookshelf
      POSTGRES_USER: bookshelf
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - pgdata:/var/lib/postgresql
    healthcheck:
      test: ["CMD", "pg_isready", "-h", "localhost", "-U", "bookshelf", "-d", "bookshelf"]
      interval: 2s
      timeout: 5s
      retries: 15

  migrate:
    <<: *django
    command: ["python", "manage.py", "migrate", "--noinput"]
    depends_on:
      db:
        condition: service_healthy

  web:
    <<: *django
    ports:
      - "8000:8000"
    depends_on:
      migrate:
        condition: service_completed_successfully

volumes:
  pgdata:

Compose ignores top-level keys that start with x-. &django names the mapping, and <<: *django merges it into a service. image: bookshelf gives the built image a fixed name. The service migrate replaces the CMD of the image with the migration command and waits for a healthy database; web waits until migrate has exited with code 0. If the migrations fail, the web server does not start with the old schema. We start the project on the empty volume, load the fixture, and count the books on the page.

docker compose ps -a also lists stopped containers. The migration container exited with code 0. When we run docker compose up -d again, for example after pulling a new version, the running services stay as they are, and the migration service runs once more and finds nothing to do.

$ docker compose up -d --build
 Image bookshelf Building 
 Image bookshelf Building 
 Image bookshelf Built 
 Image bookshelf Built 
 Volume bookshelf_pgdata Creating 
 Network bookshelf_default Creating 
 Volume bookshelf_pgdata Created 
 Network bookshelf_default Created 
 Container bookshelf-db-1 Creating 
 Container bookshelf-db-1 Created 
 Container bookshelf-migrate-1 Creating 
 Container bookshelf-migrate-1 Created 
 Container bookshelf-web-1 Creating 
 Container bookshelf-web-1 Created 
 Container bookshelf-db-1 Starting 
 Container bookshelf-db-1 Started 
 Container bookshelf-db-1 Waiting 
 Container bookshelf-db-1 Healthy 
 Container bookshelf-migrate-1 Starting 
 Container bookshelf-migrate-1 Started 
 Container bookshelf-migrate-1 Waiting 
 Container bookshelf-migrate-1 Exited 
 Container bookshelf-web-1 Starting 
 Container bookshelf-web-1 Started 
$ docker compose ps -a --format "table {{.Service}}\t{{.Status}}"
SERVICE   STATUS
db        Up 4 seconds (healthy)
migrate   Exited (0) Less than a second ago
web       Up Less than a second
$ docker compose logs migrate | tail -n 3
migrate-1  |   Applying auth.0012_alter_user_first_name_max_length... OK
migrate-1  |   Applying books.0001_initial... OK
migrate-1  |   Applying sessions.0001_initial... OK
$ docker compose exec web python manage.py loaddata books
Installed 3 object(s) from 1 fixture(s)
$ curl -s localhost:8000/ | grep -c '<li>'
3
$ docker images --format 'table {{.Repository}}\t{{.Tag}}\t{{.Size}}' bookshelf
REPOSITORY   TAG       SIZE
bookshelf    latest    215MB
$ docker compose up -d
 Container bookshelf-db-1 Running 
 Container bookshelf-web-1 Running 
 Container bookshelf-db-1 Waiting 
 Container bookshelf-db-1 Healthy 
 Container bookshelf-migrate-1 Starting 
 Container bookshelf-migrate-1 Started 
 Container bookshelf-migrate-1 Waiting 
 Container bookshelf-migrate-1 Exited 
$ docker compose logs migrate | tail -n 2
migrate-1  | Running migrations:
migrate-1  |   No migrations to apply.

A health check of the web service

The web service gets a health check too, which calls the health view. The slim image has no curl, so the check uses Python's urllib. The new lines in the web service are the healthcheck.

compose.yaml
  web:
    <<: *django
    ports:
      - "8000:8000"
    healthcheck:
      test: ["CMD", "python", "-c",
             "import urllib.request; urllib.request.urlopen('http://localhost:8000/health/')"]
      interval: 10s
      timeout: 3s
      retries: 3
    depends_on:
      migrate:
        condition: service_completed_successfully

urlopen() raises an exception for a status of 400 or more, and Python exits with code 1, so the 503 of the view marks the check as failed. The check runs every ten seconds, and three failures in a row make the container unhealthy. Compose recreates only the changed service.

When we stop the database, the health view reports the error at once: the stopped container has left the network, so the name db does not resolve. After three failed checks, the container is unhealthy; docker inspect shows the exit codes of the last checks. Docker itself does not restart an unhealthy container, but the status is visible in docker compose ps, and orchestrators and load balancers use it. When the database is back, the web service becomes healthy again; the Django connection is opened anew for each request.

$ docker compose up -d | grep web
 Container bookshelf-web-1 Recreate 
 Container bookshelf-web-1 Recreated 
 Container bookshelf-web-1 Starting 
 Container bookshelf-web-1 Started 
$ docker compose ps --format "table {{.Service}}\t{{.Status}}"
SERVICE   STATUS
db        Up 19 seconds (healthy)
web       Up 12 seconds (healthy)
$ docker compose stop db
 Container bookshelf-db-1 Stopping 
 Container bookshelf-db-1 Stopped 
$ curl -s localhost:8000/health/
{"status": "error", "error": "failed to resolve host 'db': [Errno -3] Temporary failure in name resolution"}
$ docker compose ps --format "table {{.Service}}\t{{.Status}}"
SERVICE   STATUS
web       Up 44 seconds (unhealthy)
$ docker inspect --format '{{range .State.Health.Log}}{{.ExitCode}} {{end}}' bookshelf-web-1
0 1 1 1 
$ docker compose start db
 Container bookshelf-db-1 Starting 
 Container bookshelf-db-1 Started 
$ docker compose ps --format "table {{.Service}}\t{{.Status}}"
SERVICE   STATUS
db        Up 12 seconds (healthy)
web       Up 56 seconds (healthy)

Processes in the container

docker compose exec web id shows the user that runs commands in the container, and docker compose top lists its processes: the Gunicorn master and two workers.

Everything in the container runs as root. Root in a container is restricted by the kernel, but it can change any file of the application, and a bug in the container runtime would give it more power. The application does not need any of it.

$ docker compose exec web id
uid=0(root) gid=0(root) groups=0(root)
$ docker compose top web
SERVICE  #   UID   PID    PPID   C   STIME  TTY  TIME      CMD
web      1   root  92721  92697  0   21:54  ?    00:00:00  /app/.venv/bin/python /app/.venv/bin/gunicorn config.wsgi
web      1   root  92770  92721  0   21:54  ?    00:00:00  /app/.venv/bin/python /app/.venv/bin/gunicorn config.wsgi
web      1   root  92771  92721  0   21:54  ?    00:00:00  /app/.venv/bin/python /app/.venv/bin/gunicorn config.wsgi

A non-root user

We create a system group and user in the image and switch to it with USER at the end of the Dockerfile.

Dockerfile
FROM python:3.15-slim

COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /bin/uv

WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev

COPY . .

ENV PATH="/app/.venv/bin:$PATH"
RUN DJANGO_SECRET_KEY=build-only python manage.py collectstatic --noinput

RUN groupadd --system --gid 10001 app \
    && useradd --system --uid 10001 --gid app --create-home app
USER app

CMD ["gunicorn", "config.wsgi"]

The USER instruction applies to the following instructions and to the container, so the earlier steps still run as root and the files of the project stay owned by root, read-only for the application. We set a fixed user and group id: a container shares the user ids with the host, and tools on the host, such as docker compose top, show the name of the host user with the same id. 10001 is above the range used by the host's own accounts. The home directory is for Gunicorn's control socket. We rebuild and start the project.

The processes run as the user app, which cannot change the code. Gunicorn's control socket is in the home directory of the user.

$ docker compose up -d --build
 Image bookshelf Building 
 Image bookshelf Building 
 Image bookshelf Built 
 Image bookshelf Built 
 Container bookshelf-db-1 Running 
 Container bookshelf-migrate-1 Recreate 
 Container bookshelf-migrate-1 Recreated 
 Container bookshelf-web-1 Recreate 
 Container bookshelf-web-1 Recreated 
 Container bookshelf-db-1 Waiting 
 Container bookshelf-db-1 Healthy 
 Container bookshelf-migrate-1 Starting 
 Container bookshelf-migrate-1 Started 
 Container bookshelf-migrate-1 Waiting 
 Container bookshelf-migrate-1 Exited 
 Container bookshelf-web-1 Starting 
 Container bookshelf-web-1 Started 
$ docker compose exec web id
uid=10001(app) gid=10001(app) groups=10001(app)
$ docker compose top web
SERVICE  #   UID    PID    PPID   C   STIME  TTY  TIME      CMD
web      1   10001  94035  94012  8   21:55  ?    00:00:00  /app/.venv/bin/python /app/.venv/bin/gunicorn config.wsgi
web      1   10001  94084  94035  40  21:55  ?    00:00:00  /app/.venv/bin/python /app/.venv/bin/gunicorn config.wsgi
web      1   10001  94085  94035  38  21:55  ?    00:00:00  /app/.venv/bin/python /app/.venv/bin/gunicorn config.wsgi
$ docker compose exec web touch config/hacked.py
touch: cannot touch 'config/hacked.py': Permission denied
$ curl -s localhost:8000/ | grep -c '<li>'
3
$ docker compose logs web | grep -E "Listening|Control"
web-1  | [2026-11-22 20:55:57 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
web-1  | [2026-11-22 20:55:57 +0000] [1] [INFO] Control socket listening at /home/app/.gunicorn/gunicorn.ctl

Source

Dockerfile reference

Compose file reference

uv: Using uv in Docker

Docker Hub: postgres image

Django documentation: How to deploy Django

In this article we have run a Django project in Docker: we read the settings from environment variables, wrote a Dockerfile with uv, kept secrets out of the image with .dockerignore, bound Gunicorn to all interfaces, collected the static files at build time, ran management commands with docker exec, ordered the layers for the build cache, and ran the project with PostgreSQL in Docker Compose with a volume, health checks, a migration service, and a non-root user. Related articles are Django deployment, Django settings and environment, Django database configuration, and Python Docker.

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.