How to Run Django in Docker With PostgreSQL (Step by Step)

Running Django in Docker means packaging your app, its Python version and every package into an image, then running it next to PostgreSQL with Docker Compose. You need four files next to manage.py. A Dockerfile that builds the image, an entrypoint script that migrates the database and starts Gunicorn, a compose.yaml that runs Django next to PostgreSQL, and an env file that holds your secrets. This step-by-step guide builds all four, then runs staging and production side by side on one machine.

Every command and every line of output below came from a real run on my M2 Max, with Docker Desktop 4.41.2, Python 3.14.8, Django 6.1.2, Gunicorn 26.2.0 and PostgreSQL 18.6.

The Taskboard status page in dark mode with a local badge, listing Django 6.1.2, Python 3.14.8, PostgreSQL 18.6, the container ID and one user.

That’s the demo app you’ll build, a small project called Taskboard with a status page that reports what’s running inside the container. The data is demo data only.

Why run Django in Docker?

I’m a data and backend developer who has been building with Django since 2018, and these days I run it in Docker for two reasons. First, I don’t have to worry about dependencies. Before Docker, I kept running into Python version clashes between projects, and servers that didn’t match my laptop. Second, I can run staging and production of the same Django app on one VM, each in its own containers.

Here’s the version clash fix in two commands. Each image carries its own Python, so one machine can run both at once.

$ docker run --rm python:3.12-slim python --version
Python 3.12.15
$ docker run --rm python:3.14-slim python --version
Python 3.14.8

Neither container cares which Python your laptop has. Your laptop doesn’t get a vote anymore.

The same goes for everything else the app needs. The image pins the operating system, Python, every package and the startup steps, so it behaves the same on your laptop, a teammate’s laptop, a CI runner and a server.

What does a Django Docker setup look like?

A Django Docker setup is two containers that Docker Compose starts together. One runs Django with Gunicorn, the other runs PostgreSQL, and the database files live in a volume so they outlast both. Four words cover almost everything in this guide.

  • Image. A read-only template with an operating system layer, Python, your packages and your code. You build it from a Dockerfile.
  • Container. A running copy of an image. It has its own files, processes and network address. Anything written inside it disappears when the container is deleted, unless it went to a volume.
  • Volume. Storage that lives outside the container, so data survives when containers are deleted and recreated. Your database files belong in one.
  • Docker Compose. A tool that describes several containers in one YAML file and starts them with one command. It also creates a private network so the containers can reach each other by name.
How the pieces of a Django Docker setup connect Your browser calls localhost on port 8000. Docker forwards that to the web container, where Gunicorn runs Django. The web container talks to the db container by the hostname db on port 5432. Both containers sit on a private network that Compose creates. The database files live in a named volume called postgres_data. Private network made by Compose Your browser web container Django + Gunicorn db container PostgreSQL 18 port 8000 host db, port 5432 postgres_data
The two containers share a private network, so Django finds PostgreSQL by the name db. The database files live in a named volume, outside the container.

The web container reaches PostgreSQL at the hostname db. Compose gives every service a hostname that matches its name, so you never hunt for an IP address.

Here’s every file you’ll create, and the step that explains it.

File What it does Step
requirements.txt Pins Django, Gunicorn, WhiteNoise and the PostgreSQL driver Step 1
config/settings.py Reads secrets and the database address from environment variables Step 2
pages/views.py, config/urls.py and a template Add a health check URL and the status page Step 3
healthcheck.py Lets Docker ask whether the app answers Step 3
Dockerfile Builds the image Step 4
.dockerignore Keeps secrets and junk out of the image Step 5
entrypoint.sh Migrates and collects static files on every start Step 6
compose.yaml Runs Django and PostgreSQL together Step 7
.env Holds your secrets and settings Step 8
.env.staging and .env.production Run two copies on one machine Step 10
compose.dev.yaml Mounts your code for live reload Step 11

What do you need before you start?

Check that Docker works. These are the versions I tested with.

$ docker --version
Docker version 28.1.1, build 4eba377
$ docker compose version
Docker Compose version v2.35.1-desktop.1

Docker Desktop’s About window shows the same versions.

Docker Desktop’s About window showing version 4.41.2, Engine 28.1.1, Compose v2.35.1, Credential Helper v0.9.3 and Kubernetes v1.32.2.

Docker Desktop 4.41.2 on my M2 Max.

Compose is docker compose with a space. The old docker-compose with a hyphen is the retired Python version, and tutorials that still use it are older than they look.

The twelve steps at a glance

Steps 1 to 8 write the files. Step 9 runs everything, and Steps 10 to 12 cover staging and production, live reload and backups.

  1. Create the Django project.
  2. Read settings from environment variables.
  3. Add a health check and a status page.
  4. Write the Dockerfile for Django.
  5. Keep secrets out with .dockerignore.
  6. Write the entrypoint script.
  7. Write the Django Docker Compose file.
  8. Create the env file.
  9. Build and run Django in Docker.
  10. Run staging and production on one machine.
  11. Set up live reload for development.
  12. Back up and restore the database.

Step 1. Create the Django project

Skip this if you already have a project. Otherwise, make a folder, a virtual environment (a private set of Python packages for one project), and let Django create a project and one app called pages.

mkdir taskboard && cd taskboard
python3 -m venv venv
source venv/bin/activate
pip install "Django>=6.1,<6.2"
django-admin startproject config .
python manage.py startapp pages

No Python on your machine? Docker can create the project for you. This runs startproject in a throwaway container and writes the files into your current folder.

docker run --rm -v "$PWD":/app -w /app python:3.14-slim sh -c "pip install 'Django>=6.1,<6.2' && django-admin startproject config ."

Now create requirements.txt in the project folder.

Django==6.1.2
gunicorn==26.2.0
whitenoise==6.12.0
psycopg[binary]==3.3.6
dj-database-url==3.1.2
  • gunicorn is a production web server for Python apps. Django’s runserver is for development only, and the Django docs say so in capital letters.
  • whitenoise lets Django serve its own CSS and JavaScript efficiently, so you don’t need a separate web server for static files.
  • psycopg[binary] is the PostgreSQL driver. The [binary] part ships it precompiled, so the image needs no C compiler.
  • dj-database-url turns one DATABASE_URL string into Django’s DATABASES setting.

I pinned exact versions, so your build installs what mine did. Bump them on purpose, not by accident.

Step 2. Read settings from environment variables

The rule for containers is simple. The image stays the same everywhere, and configuration comes in from outside through environment variables. Secrets and the database address never get baked into the image or committed to git. My Django and Anthropic SDK tutorial keeps its API key out of the code the same way.

Open config/settings.py. Add two imports at the top.

import os
from pathlib import Path

import dj_database_url

Replace the SECRET_KEY, DEBUG and ALLOWED_HOSTS lines with this block.

# No default on purpose. The app refuses to start without a real key.
SECRET_KEY = os.environ['SECRET_KEY']

# Anything other than the word "true" means False.
DEBUG = os.environ.get('DEBUG', 'false').lower() == 'true'

ALLOWED_HOSTS = [
    host.strip()
    for host in os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',')
    if host.strip()
]

# Needed once you serve over HTTPS, for example https://app.example.com
CSRF_TRUSTED_ORIGINS = [
    origin.strip()
    for origin in os.environ.get('CSRF_TRUSTED_ORIGINS', '').split(',')
    if origin.strip()
]

# A label for the status page, such as staging or production.
APP_ENV = os.environ.get('APP_ENV', 'local')

A hard-coded fallback key is how a “temporary” setting ends up in production for three years. No default means a missing key crashes the app on day one instead.

Add 'pages' to INSTALLED_APPS, and put WhiteNoise right after SecurityMiddleware. The WhiteNoise docs ask for that exact spot.

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    # ...the rest stays as generated
]

Replace DATABASES so it reads DATABASE_URL.

DATABASES = {
    'default': dj_database_url.config(
        # Falls back to SQLite when DATABASE_URL is not set.
        default=f"sqlite:///{BASE_DIR / 'db.sqlite3'}",
        conn_max_age=60,
    )
}

Without DATABASE_URL, it falls back to SQLite, the database my ORM and migrations tutorial uses.

Then tell Django where to collect static files, and switch to WhiteNoise’s storage.

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'

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

This storage compresses your files and adds a hash to each name, so style.css becomes something like style.4f3a9c.css and browsers can cache it forever. The catch is that collectstatic must run before any page renders. The entrypoint in Step 6 runs it on every start.

Step 3. Add a health check and a status page

Docker can ask a container “are you healthy?” every few seconds. Compose can wait for the answer before it starts things that depend on it. You need a cheap URL that proves Django is up and can reach the database.

Put both views in pages/views.py. The second one feeds the status page.

import platform
import socket

import django
from django.conf import settings
from django.contrib.auth.models import User
from django.db import connection
from django.http import HttpResponse
from django.shortcuts import render

def healthz(request):
    # One tiny query proves the database connection works.
    with connection.cursor() as cursor:
        cursor.execute('SELECT 1')
    return HttpResponse('ok', content_type='text/plain')

def home(request):
    with connection.cursor() as cursor:
        cursor.execute('SHOW server_version')
        db_version = cursor.fetchone()[0]
    context = {
        'app_env': settings.APP_ENV,
        'django_version': django.get_version(),
        'python_version': platform.python_version(),
        'db_version': db_version,
        'hostname': socket.gethostname(),
        'user_count': User.objects.count(),
    }
    return render(request, 'pages/home.html', context)

Wire them up in config/urls.py.

from django.contrib import admin
from django.urls import path

from pages import views

urlpatterns = [
    path('', views.home),
    path('healthz', views.healthz),
    path('admin/', admin.site.urls),
]

Create pages/templates/pages/home.html. The stylesheet it loads only makes the page look nice, so I’ve left it out here.

{% load static %}<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Taskboard ({{ app_env }})</title>
  <link rel="stylesheet" href="{% static 'pages/style.css' %}">
</head>
<body>
  <main class="card">
    <header>
      <h1>Taskboard</h1>
      <span class="badge badge-{{ app_env }}">{{ app_env }}</span>
    </header>
    <p class="lead">Running in Docker, served by Gunicorn, backed by PostgreSQL.</p>
    <dl>
      <div><dt>Django</dt><dd>{{ django_version }}</dd></div>
      <div><dt>Python</dt><dd>{{ python_version }}</dd></div>
      <div><dt>PostgreSQL</dt><dd>{{ db_version }}</dd></div>
      <div><dt>Container</dt><dd><code>{{ hostname }}</code></dd></div>
      <div><dt>Users in this database</dt><dd>{{ user_count }}</dd></div>
    </dl>
    <footer><a href="/admin/">Open the admin</a><span>Demo data only</span></footer>
  </main>
</body>
</html>

Now the script Docker runs for the health check. Save it as healthcheck.py next to manage.py.

"""Docker runs this to check the app. Exit code 0 means healthy."""
import os
import sys
import urllib.error
import urllib.request

# Django answers 400 when the Host header is not in ALLOWED_HOSTS,
# so send the first allowed host.
host = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',')[0].strip()

request = urllib.request.Request(
    'http://localhost:8000/healthz',
    headers={'Host': host},
)

try:
    with urllib.request.urlopen(request, timeout=5) as response:
        sys.exit(0 if response.status == 200 else 1)
except (urllib.error.URLError, OSError):
    sys.exit(1)

Docker treats exit code 0 as healthy and 1 as unhealthy. The try and except block turns a refused connection or a timeout into a clean exit code 1 instead of a traceback, and my Python exception handling guide covers how that works.

Why a Python script and not curl?

The slim Python image has neither curl nor wget. I checked.

$ docker run --rm python:3.14-slim sh -c 'command -v curl || echo "no curl"; command -v wget || echo "no wget"'
no curl
no wget

Python’s standard library is already in there, so the check costs nothing extra to install.

Why send a Host header?

Django checks the Host header of every request against ALLOWED_HOSTS and answers 400 when it doesn’t match. A check that sends the wrong host fails even though the app is fine. Taking the first allowed host from the same environment variable keeps the check and the app in agreement.

Step 4. Write the Dockerfile for Django

A Dockerfile is a recipe Docker runs top to bottom to build your image. Create a file named exactly Dockerfile, with no extension.

FROM python:3.14-slim

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1

WORKDIR /app

# Install dependencies first, so Docker can cache this layer.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Then copy the rest of the project.
COPY . .

# An unprivileged user that owns the folder collectstatic writes to.
RUN addgroup --system app && adduser --system --ingroup app app \
    && mkdir -p /app/staticfiles \
    && chown app:app /app/staticfiles \
    && chmod +x /app/entrypoint.sh

USER app

EXPOSE 8000

ENTRYPOINT ["/app/entrypoint.sh"]

CMD ["gunicorn", "config.wsgi:application", \
     "--bind", "0.0.0.0:8000", \
     "--workers", "3", \
     "--no-control-socket", \
     "--access-logfile", "-", \
     "--error-logfile", "-"]
  • FROM python:3.14-slim starts from the official Python image on Debian, minus most extras. On my Mac the slim image takes 204 MB of disk and the full python:3.14 image takes 1.62 GB.
  • PYTHONUNBUFFERED=1 makes print() and logging show up in docker compose logs right away instead of sitting in a buffer.
  • PYTHONDONTWRITEBYTECODE=1 stops Python from writing .pyc files into the image.
  • WORKDIR /app sets the working folder for everything after it.
  • addgroup and adduser create an unprivileged user. Containers run as root by default, and if someone ever exploits your app, root is a much better starting point for them than a user who owns one folder.
  • USER app switches to that user for everything after it, including the running container.
  • EXPOSE 8000 documents the port. It doesn’t publish anything. Compose does that.
  • ENTRYPOINT ["/app/entrypoint.sh"] runs the startup script from Step 6 every time a container starts.
  • CMD [...] is the command the entrypoint hands over to when it’s done. By default that’s Gunicorn, and you can swap in any other command, which Step 6 shows.

The Gunicorn options in CMD are worth a line each.

  • --bind 0.0.0.0:8000 listens on every network interface inside the container. Binding to 127.0.0.1 gives you the classic “it runs but I can’t open it” problem.
  • --workers 3 starts three worker processes. A common starting point is two per CPU core plus one, and you can tune it later.
  • --no-control-socket turns off a feature Gunicorn added in version 25.1. It tries to create a control socket in the user’s home folder, and our system user has no home folder. Without this flag, every start logs a permission error.
  • --access-logfile - and --error-logfile - send logs to the terminal, which is where Docker collects them.

The bracket form of ENTRYPOINT and CMD skips an extra shell, so stop signals from docker stop reach Gunicorn and it finishes its requests cleanly.

You can check the user once the container runs. Docker Desktop’s Exec tab opens a shell inside it, and whoami answers app, not root.

Docker Desktop’s Exec tab in the staging web container, where whoami prints app and python –version prints Python 3.14.8.

The staging web container from Step 10.

Why does the order of COPY matter?

Docker caches each instruction as a layer and reuses it when nothing it depends on has changed. Your code changes all the time, but requirements.txt rarely does. Copying and installing requirements before the rest of the code means a code edit doesn’t reinstall every package.

I timed it on my M2 Max. I changed one line in views.py and rebuilt, three times with this Dockerfile and three times with a version that copies all the code first and installs after. The median rebuild took 0.48 seconds with this order and 7.42 seconds with the other, on a project with five packages. Every package you add makes the slow order slower, on every rebuild, all day.

Docker Desktop shows the same split. Click Images, then your image, and it lists every layer with its size. The pip install layer weighs 84 MB and the COPY . . layer after it weighs 135 KB. A code edit rebuilds from that small layer onward and reuses the big one.

Docker Desktop’s layer list for the staging image. The pip install layer is 84.16 MB and the code layer after it is 135.17 KB.

Layers 8 to 15 of the staging image from Step 10. Layers 0 to 7 come from python:3.14-slim.

Step 5. Keep secrets out with .dockerignore

When you build, Docker sends your project folder to the builder, and COPY . . copies all of it into the image. A .dockerignore file keeps junk and secrets out. Create it next to the Dockerfile.

# Python
venv/
.venv/
__pycache__/
*.pyc

# Git
.git/

# Secrets and local data never go into an image
.env*
!.env.example
db.sqlite3
backup.sql

# Built inside the container
staticfiles/

# Editor and OS files
.vscode/
.idea/
.DS_Store

The .env* line matters most. It blocks .env, .env.staging and .env.production at once, and the !.env.example line lets the harmless example file through. An image is easy to share by accident, and a secret inside an image layer is very hard to get back out.

Here’s what actually landed in my image. No venv, no .env, no database file.

$ docker run --rm --entrypoint ls taskboard-web -a /app
.
..
.dockerignore
.env.example
.gitignore
Dockerfile
compose.dev.yaml
compose.yaml
config
entrypoint.sh
healthcheck.py
manage.py
pages
requirements.txt
staticfiles

Docker Desktop shows the same thing. Click a running container and open its Files tab.

Docker Desktop’s Files tab for the staging web container, showing the app folder with .env.example as its only env file.

The staging container from Step 10. Its .env.staging file stayed out of the image.

Use the same patterns in .gitignore, so secrets stay out of git too.

venv/
__pycache__/
db.sqlite3
staticfiles/
backup.sql
.env*
!.env.example

Step 6. Write the entrypoint script

Every time the container starts, two things should happen before anything else. Apply migrations and collect static files. Save this as entrypoint.sh next to manage.py.

#!/bin/sh
# Runs inside the container every time it starts.
set -e

echo "==> Running database migrations"
python manage.py migrate --noinput

echo "==> Collecting static files"
python manage.py collectstatic --noinput --clear

# Run the container's command: Gunicorn by default, or a one-off command.
exec "$@"
  • set -e stops the script at the first failure. If a migration fails, you want the container to crash loudly, not serve a broken app.
  • --noinput stops the commands from asking questions. Nobody is there to answer inside a container.
  • exec "$@" replaces the shell with whatever command the container was given. Normally that’s the Gunicorn CMD from the Dockerfile.

That last line matters more than it looks. Plenty of tutorials end the entrypoint with a hard-coded exec gunicorn ..., which means docker compose run --rm web python manage.py test quietly ignores your command and starts a web server instead. Your tests never run, and nothing tells you. With exec "$@", a one-off command runs after the setup steps.

$ docker compose run --rm web python manage.py test
==> Running database migrations
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  No migrations to apply.
==> Collecting static files
...
Found 0 test(s).
System check identified no issues (0 silenced).

----------------------------------------------------------------------
Ran 0 tests in 0.000s

NO TESTS RAN

The demo has no tests, so zero ran, but the command reached Django’s test runner. I cut the static files lines.

Windows users, one warning. If this file is saved with Windows line endings, the container fails with exec /app/entrypoint.sh: no such file or directory, which is a spectacularly unhelpful way to say “wrong line endings.” Save it with LF endings, and add a .gitattributes file with this line so git never converts it.

*.sh text eol=lf

Running migrations at startup is fine for one web container. Once you run several copies of it, run migrations once as a separate deploy step, so the copies don’t race each other.

Step 7. Write the Django Docker Compose file

Create compose.yaml next to the Dockerfile. That’s the file name the Compose docs prefer, and docker-compose.yml still works too.

services:
  db:
    image: postgres:18-alpine
    restart: unless-stopped
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in your env file}
      POSTGRES_DB: app
    volumes:
      - postgres_data:/var/lib/postgresql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U postgres -d app"]
      interval: 5s
      timeout: 5s
      retries: 10

  web:
    build: .
    restart: unless-stopped
    environment:
      SECRET_KEY: ${SECRET_KEY:?set SECRET_KEY in your env file}
      DEBUG: ${DEBUG:-false}
      ALLOWED_HOSTS: ${ALLOWED_HOSTS:-localhost,127.0.0.1}
      CSRF_TRUSTED_ORIGINS: ${CSRF_TRUSTED_ORIGINS:-}
      APP_ENV: ${APP_ENV:-local}
      DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@db:5432/app
    ports:
      - "${PORT:-8000}:8000"
    healthcheck:
      test: ["CMD", "python", "healthcheck.py"]
      interval: 10s
      timeout: 5s
      retries: 3
      start_period: 30s
    depends_on:
      db:
        condition: service_healthy

volumes:
  postgres_data:

What does the db service do?

  • postgres:18-alpine pins the major version. Never use latest for a database, because a surprise major upgrade won’t start on old data files.
  • ${POSTGRES_PASSWORD:?...} fills the value from your env file. The :? part stops Compose with that message if the variable is missing, instead of starting a database with an empty password.
  • postgres_data:/var/lib/postgresql stores the data in a named volume that survives docker compose down. PostgreSQL 18 moved the data folder, so the volume now mounts at /var/lib/postgresql. Tutorials written for version 17 and older mount /var/lib/postgresql/data, and version 18 refuses to start with that layout.
  • pg_isready -h 127.0.0.1 reports when PostgreSQL accepts connections. The -h 127.0.0.1 part matters on the very first start. The image runs a temporary server that only listens on a local socket while it creates your database, and checking over TCP stops the health check from passing too early.

What does the web service do?

  • build: . builds the image from the Dockerfile in this folder.
  • environment: passes each setting into the container. Compose fills every ${...} from your env file, and ${DEBUG:-false} means “use DEBUG, or false if it’s empty.”
  • DATABASE_URL points at the host db, which is the database service’s name. Don’t use localhost here. Inside the web container, localhost is the web container itself.
  • ports publishes the container’s port 8000 on your machine, on whatever PORT says.
  • healthcheck runs healthcheck.py every 10 seconds. start_period gives Django 30 seconds to migrate and boot before failures count.
  • depends_on with condition: service_healthy waits until the database passes its health check. Plain depends_on only waits for the container to start, which is not the same as ready. The startup order docs explain the difference.

Listing every variable under environment: is a trade-off. You type each name twice, once here and once in the env file. In return, one compose file can serve several environments, which Step 10 needs. Just remember that a variable missing from this list quietly falls back to the default in settings.py.

There’s no version: line at the top. Compose ignores it now and prints a warning telling you to delete it, so copying it from an old tutorial gets you a free nag on every command.

Step 8. Create the env file

Create a file named .env next to compose.yaml. Compose reads it automatically to fill the ${...} placeholders.

SECRET_KEY=replace-me
POSTGRES_PASSWORD=replace-me
ALLOWED_HOSTS=localhost,127.0.0.1
DEBUG=false
APP_ENV=local
PORT=8000

Generate real random values instead of typing them.

python3 -c "import secrets; print(secrets.token_urlsafe(50))"
openssl rand -hex 24

Use the first for SECRET_KEY and the second for POSTGRES_PASSWORD. The password should be hex, because random strings with /, + or @ in them break the postgresql://user:password@host address in DATABASE_URL.

Your .gitignore already keeps .env out of git. Commit a .env.example with empty secrets instead, so teammates know what to fill in.

SECRET_KEY=
POSTGRES_PASSWORD=
ALLOWED_HOSTS=localhost,127.0.0.1
DEBUG=false
APP_ENV=local
PORT=8000

Step 9. Build and run Django in Docker

From the project folder, build the image and start both containers in the background.

docker compose up -d --build

The first build downloads the base images and installs your packages, so it takes a minute. Later builds reuse the cache. Check the state.

$ docker compose ps
NAME              IMAGE                COMMAND                  SERVICE   CREATED          STATUS                    PORTS
taskboard-db-1    postgres:18-alpine   "docker-entrypoint.s…"   db        12 seconds ago   Up 11 seconds (healthy)   5432/tcp
taskboard-web-1   taskboard-web        "/app/entrypoint.sh …"   web       12 seconds ago   Up 6 seconds (healthy)    0.0.0.0:8000->8000/tcp

Both containers say healthy. While the web check is still warming up you’ll see health: starting instead. Read the startup logs. I cut the middle of the migration list.

$ docker compose logs web
web-1  | ==> Running database migrations
web-1  | Operations to perform:
web-1  |   Apply all migrations: admin, auth, contenttypes, sessions
web-1  | Running migrations:
web-1  |   Applying contenttypes.0001_initial... OK
web-1  |   Applying auth.0001_initial... OK
web-1  |   ...
web-1  |   Applying sessions.0001_initial... OK
web-1  | ==> Collecting static files
web-1  | 
web-1  | 131 static files copied to '/app/staticfiles', 393 post-processed.
web-1  | [2026-10-13 10:48:44 +0000] [1] [INFO] Starting gunicorn 26.2.0
web-1  | [2026-10-13 10:48:44 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
web-1  | [2026-10-13 10:48:44 +0000] [1] [INFO] Using worker: sync
web-1  | [2026-10-13 10:48:44 +0000] [25] [INFO] Booting worker with pid: 25
web-1  | [2026-10-13 10:48:44 +0000] [26] [INFO] Booting worker with pid: 26
web-1  | [2026-10-13 10:48:45 +0000] [27] [INFO] Booting worker with pid: 27
web-1  | 127.0.0.1 - - [13/Oct/2026:10:48:48 +0000] "GET /healthz HTTP/1.1" 200 2 "-" "Python-urllib/3.14"

Migrations ran, static files were collected, Gunicorn started with three workers, and the first health check got a 200. Now create an admin user. It asks for a username, an email and a password.

docker compose exec web python manage.py createsuperuser

Open http://localhost:8000/ for the status page, then http://localhost:8000/admin/ and log in.

The Django admin users list in dark mode, fully styled, showing one user named admin with the email admin@example.com and staff status checked.

A fully styled admin means WhiteNoise and collectstatic work. A plain, unstyled page means they don’t, and the troubleshooting section below covers why.

Now prove the data survives. Stop and remove both containers, start them again, and list the users.

$ docker compose down
$ docker compose up -d
$ docker compose exec web python manage.py shell -c "from django.contrib.auth.models import User; print(list(User.objects.values_list('username', flat=True)))"
12 objects imported automatically (use -v 2 for details).

['admin']

The first line is Django 6’s shell telling you it imported your models for you. The user is still there, because the database lives in the postgres_data volume and not in the container. docker compose down keeps volumes. docker compose down -v deletes them, along with your database, so only add -v when you mean it.

Step 10. Run staging and production on one machine

This is my second reason for using Docker. I run staging and production of a Django app on one VM, each in its own containers, and they don’t step on each other.

Here’s one way to set it up with the files you already have. Make one env file per environment, and give each its own project name. Compose uses the project name to keep containers, networks and volumes apart, and the Compose docs describe exactly this use, the same compose.yaml deployed twice on one machine.

Create .env.staging.

COMPOSE_PROJECT_NAME=taskboard-staging
SECRET_KEY=a-different-random-key
POSTGRES_PASSWORD=a-different-random-password
ALLOWED_HOSTS=localhost,127.0.0.1
DEBUG=false
APP_ENV=staging
PORT=8001

Create .env.production the same way, with COMPOSE_PROJECT_NAME=taskboard-production, APP_ENV=production, PORT=8002, and its own secrets. Then start both.

docker compose --env-file .env.staging up -d --build
docker compose --env-file .env.production up -d --build

Compose read the project name from each file and created a separate network and volume for each one.

 Network taskboard-staging_default  Created
 Volume "taskboard-staging_postgres_data"  Created
 Network taskboard-production_default  Created
 Volume "taskboard-production_postgres_data"  Created

Four containers, two stacks, one machine.

$ docker ps --filter name=taskboard --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
NAMES                        STATUS                    PORTS
taskboard-production-web-1   Up 7 seconds (healthy)    0.0.0.0:8002->8000/tcp
taskboard-production-db-1    Up 12 seconds (healthy)   5432/tcp
taskboard-staging-web-1      Up 13 seconds (healthy)   0.0.0.0:8001->8000/tcp
taskboard-staging-db-1       Up 19 seconds (healthy)   5432/tcp

I created an admin user in staging only. The status pages prove each environment has its own database.

Two Taskboard status pages side by side, one with a staging badge and one user, the other with a production badge and zero users.

Two screenshots joined into one image, of localhost:8001 and localhost:8002.

Docker Desktop shows each Compose project as its own group, with its web and db containers inside.

Docker Desktop’s Containers view filtered to taskboard, with the production and staging groups each running a web and a db container.

I typed taskboard in the search box, so other projects on my Mac stay out of the shot.

Each project gets its own volume too, so staging and production never share a database.

Docker Desktop’s Volumes view with the taskboard-production and taskboard-staging postgres_data volumes, both in use.

The green dot means a running container uses the volume.

Every command for these stacks needs its --env-file, including ps, logs, exec and down. Leave it off and Compose talks to the default project from .env instead.

docker compose --env-file .env.staging logs -f web
docker compose --env-file .env.production exec web python manage.py createsuperuser
docker compose --env-file .env.staging down

Both stacks here run the same code from the same folder. In real life, staging runs newer code than production. On my VM, each one deploys from its own git checkout. On a real server you’d also put a reverse proxy such as Caddy or Nginx in front, so staging.example.com and example.com reach the right port over HTTPS. To see what nginx, a cache and more workers do under real load, learn system design by growing a Django app one measured step at a time.

Step 11. Set up live reload for development

The setup so far behaves like production. The code is copied into the image, so every change needs a rebuild. For daily work you want edits to show up right away. Create compose.dev.yaml.

# Development only. Use it with
# docker compose -f compose.yaml -f compose.dev.yaml up
services:
  web:
    # Skip the entrypoint and use Django's auto-reloading dev server.
    entrypoint: []
    command: python manage.py runserver 0.0.0.0:8000
    environment:
      DEBUG: "true"
    volumes:
      # Mount your code over /app, so edits show up right away.
      - .:/app

Start it by naming both files.

docker compose -f compose.yaml -f compose.dev.yaml up -d --build

Your folder is now mounted over /app, so saving a file restarts Django’s dev server. This is what the logs printed after I saved views.py.

web-1  | /app/pages/views.py changed, reloading.
web-1  | Watching for file changes with StatReloader
web-1  | Performing system checks...
web-1  | 
web-1  | System check identified no issues (0 silenced).
web-1  | October 13, 2026 - 10:50:14
web-1  | Django version 6.1.2, using settings 'config.settings'
web-1  | Starting WSGI development server at http://0.0.0.0:8000/

The entrypoint is skipped in this mode, so run migrations yourself with docker compose exec web python manage.py migrate. Files you create with makemigrations land in your real project folder, because it’s mounted.

Why not name it compose.override.yaml, which many tutorials use? Compose merges that file automatically into every command in the folder. Add it, and docker compose --env-file .env.production up quietly runs the dev server with DEBUG on. A file you have to name with -f can’t sneak into production.

On a Linux host, files in a bind mount keep their owner from the host, so the container’s app user may not be able to write to them. Docker Desktop on a Mac handles that for you, which is why it worked on mine without changes.

Step 12. Back up and restore the database

Volumes protect you from deleted containers. They don’t protect you from mistakes, a dead disk or a stray down -v. Back up to a file on your machine.

docker compose exec -T db pg_dump -U postgres --clean --if-exists app > backup.sql

The -T flag turns off the terminal Docker would otherwise attach, so the output can go into a file. --clean --if-exists adds commands that drop each table before recreating it, which you need because the entrypoint has already created every table by the time you restore.

To restore, stop the web container so nothing writes during the restore, load the file, and start web again.

docker compose stop web
docker compose exec -T db psql -v ON_ERROR_STOP=1 -U postgres -d app < backup.sql
docker compose start web

ON_ERROR_STOP=1 makes psql stop and exit with an error at the first failure. Without it, psql prints the errors, keeps going and exits as if everything worked, as the psql docs explain under exit status.

I tested the round trip. I took a backup, deleted the admin user, restored, and checked.

$ docker compose exec web python manage.py shell -c "from django.contrib.auth.models import User; User.objects.filter(username='admin').delete(); print(User.objects.count())"
12 objects imported automatically (use -v 2 for details).

0
$ docker compose exec web python manage.py shell -c "from django.contrib.auth.models import User; print(list(User.objects.values_list('username', flat=True)))"
12 objects imported automatically (use -v 2 for details).

['admin']

For a real server, run the backup on a schedule and copy the file somewhere that isn’t the same machine. A backup on the disk that just died is a very confident way to lose everything twice.

Which Docker commands will you use every day?

Day to day, you’ll mostly start the stack with up, read it with logs, and run Django commands with exec or run. The list below covers most days. For the staging and production stacks, add their --env-file to each one.

docker compose ps                                       # what's running
docker compose logs -f web                              # follow the web logs
docker compose exec web python manage.py migrate        # run a command in the running container
docker compose exec web python manage.py shell          # Django shell
docker compose run --rm web python manage.py test       # one-off command in a fresh container
docker compose exec web sh                              # a shell inside the container
docker compose up -d --build                            # rebuild after changing code or requirements
docker compose restart web                              # restart one service
docker compose exec db psql -U postgres -d app          # open the database
docker system df                                        # disk used by images and volumes

exec runs a command inside a container that’s already running. run --rm starts a new container from the image, runs the command, and deletes the container after. Use exec to poke at live state and run for one-off jobs like tests.

Docker Desktop covers the same ground if you’d rather click. Open a container and its Logs tab follows the output like logs -f, and its Exec tab opens a shell like exec web sh.

Docker Desktop’s Logs tab for the staging web container, showing migrations, collectstatic, then Gunicorn 26.2.0 starting its workers.

The staging web container starting up, from the entrypoint in Step 6 to Gunicorn.

Its Stats tab graphs CPU, memory, disk and network use live, and docker stats prints the same numbers in the terminal. With three Gunicorn workers, the staging web container sat at about 153 MB of memory.

Docker Desktop’s memory chart for the staging web container. It reads 152.6 MB used out of 7.65 GB and stays flat across about 12 minutes.

Memory use of the staging web container. The 7.65 GB ceiling is the memory available inside Docker Desktop’s virtual machine.

To reclaim disk space, docker image prune removes unused images. Read what it lists before you confirm. I didn’t run it on my machine for this guide, because other projects live there too.

Does Django in Docker work on Apple Silicon?

Yes. My M2 Max runs arm64 images natively. python:3.14-slim and postgres:18-alpine publish arm64 builds, and psycopg[binary] ships arm64 Linux wheels for Python 3.14, so nothing compiles and nothing runs under emulation.

You can check it from inside a container. In Docker Desktop’s Exec tab for the database container, PostgreSQL reports an aarch64 build, which means 64-bit ARM.

Docker Desktop’s Exec tab in the staging database container, where PostgreSQL reports version 18.6 on aarch64 and lists ten Django tables.

The staging database from Step 10, on my M2 Max.

The catch is deploying. Many cloud servers still use amd64 (Intel and AMD) processors, and an image built on a Mac is arm64 by default. Run that on an amd64 server and it fails with exec format error. Build for the server’s platform instead.

$ docker build --platform linux/amd64 -t taskboard:amd64 .
$ docker image inspect --format '{{.Os}}/{{.Architecture}}' taskboard:amd64
linux/amd64
$ docker image inspect --format '{{.Os}}/{{.Architecture}}' taskboard-web
linux/arm64

The first build is the one for the server. The second is the native one from Step 9.

I couldn’t reproduce exec format error myself, because Docker Desktop quietly runs amd64 images through emulation on a Mac. A real amd64 server won’t do you that favor. The multi-platform build docs cover building both at once and pushing them to a registry.

The emulation itself is a Docker Desktop setting. It lives in Settings, General, under Virtual Machine Options. With the Rosetta box checked, Docker Desktop uses Apple’s Rosetta to speed up amd64 emulation.

Docker Desktop’s Virtual Machine Options, with Apple Virtualization framework selected and Rosetta emulation for amd64 turned on.

Docker Desktop 4.41.2 on my M2 Max.

How do you fix common Django Docker errors?

I triggered each of these on purpose. The message under each heading is what Docker or Django printed. Here they are at a glance.

Error Usual cause Fix
Port is already allocated Another app uses port 8000 Change PORT in .env
Entrypoint says no such file or directory Windows line endings Save as LF and add .gitattributes
Entrypoint says permission denied The script isn’t executable Keep chmod +x in the Dockerfile
Required variable is missing The env file lacks it Add it or pass the right --env-file
Django can’t reach the database localhost in DATABASE_URL Use the service name db
Password authentication failed Password changed after the volume was created Set the old one back or use ALTER USER
Missing staticfiles manifest entry collectstatic didn’t run Let the entrypoint run it
PostgreSQL 18 won’t start Volume mounted at the old /data path Mount /var/lib/postgresql
400 Bad Request, empty logs Host missing from ALLOWED_HOSTS Add it and recreate the container
Gunicorn control server error No home folder for the control socket Add --no-control-socket
Version is obsolete An old version line Delete the line

Why does Docker say the port is already allocated?

docker: Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint taskboard-porttest (18fab3be92185f9e3ee76ef7324405c34cb3ad6effe97564e2af11efb410708a): Bind for 0.0.0.0:8000 failed: port is already allocated

Something else on your machine already uses port 8000. Change PORT in .env, for example to 8080, and run docker compose up -d again.

Why does the entrypoint say “no such file or directory” when the file exists?

exec /app/entrypoint.sh: no such file or directory

The script has Windows line endings, so Linux looks for a program literally named /bin/sh plus an invisible carriage return. Convert the file to LF endings and rebuild. Step 6 has the .gitattributes line that prevents it.

Why does the entrypoint say “permission denied”?

docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: error during container init: exec: "/app/entrypoint.sh": permission denied: unknown

The script isn’t executable. The Dockerfile’s chmod +x /app/entrypoint.sh fixes it. Make sure the line is there and rebuild with --build.

Why does Compose say a required variable is missing?

error while interpolating services.web.environment.SECRET_KEY: required variable SECRET_KEY is missing a value: set SECRET_KEY in your env file

That’s the :? check from Step 7 doing its job. The variable is missing from .env, the file isn’t named exactly .env, or you passed a different --env-file. Run docker compose config to see the final configuration with every variable filled in, and keep that output to yourself, because it prints your secrets.

Why can’t Django reach the database?

django.db.utils.OperationalError: connection failed: connection to server at "127.0.0.1", port 5432 failed: Connection refused
Multiple connection attempts failed. All failures were:
- host: 'localhost', port: 5432, hostaddr: '::1': connection failed: connection to server at "::1", port 5432 failed: Connection refused
- host: 'localhost', port: 5432, hostaddr: '127.0.0.1': connection failed: connection to server at "127.0.0.1", port 5432 failed: Connection refused

DATABASE_URL points at localhost, which inside the web container is the web container. Use the service name, db. A typo in the name gives a different error.

django.db.utils.OperationalError: failed to resolve host 'database': [Errno -2] Name or service not known

Why does PostgreSQL say password authentication failed?

django.db.utils.OperationalError: connection failed: connection to server at "172.23.0.2", port 5432 failed: FATAL:  password authentication failed for user "postgres"

PostgreSQL reads POSTGRES_PASSWORD only the first time it creates an empty volume. Change the password in .env later and the volume still holds the old one. Either set the old password back, change it inside psql with ALTER USER, or, if the data doesn’t matter, delete the volume with docker compose down -v and start fresh.

Why does Django say “Missing staticfiles manifest entry”?

    raise ValueError(
ValueError: Missing staticfiles manifest entry for 'pages/style.css'

The manifest storage from Step 2 can’t find a file because collectstatic hasn’t run in that container. The entrypoint runs it on every start, including docker compose run, so you’ll only see this when something skips the entrypoint. I got it with --entrypoint "". The same thing happens in CI when tests run outside Docker, so run collectstatic before your tests there.

Why won’t PostgreSQL 18 start with my old volume?

Error: in 18+, these Docker images are configured to store database data in a
       format which is compatible with "pg_ctlcluster" (specifically, using
       major-version-specific directory names).  This better reflects how
       PostgreSQL itself works, and how upgrades are to be performed.

       See also https://github.com/docker-library/postgres/pull/1259

       Counter to that, there appears to be PostgreSQL data in:
         /var/lib/postgresql/data (unused mount/volume)

       This is usually the result of upgrading the Docker image without
       upgrading the underlying database using "pg_upgrade" (which requires both
       versions).

       The suggested container configuration for 18+ is to place a single mount
       at /var/lib/postgresql which will then place PostgreSQL data in a
       subdirectory, allowing usage of "pg_upgrade --link" without mount point
       boundary issues.

       See https://github.com/docker-library/postgres/issues/37 for a (long)
       discussion around this process, and suggestions for how to do so.

You mounted the volume at /var/lib/postgresql/data, the path from PostgreSQL 17 and older tutorials. Mount it at /var/lib/postgresql as in Step 7. If that volume holds real data from an older version, you need pg_upgrade or a dump and restore, not just a new tag.

The path moved because the image now keeps data in a folder named after the major version. Mount a volume at /var/lib/postgresql and PostgreSQL 18 writes into 18/docker inside it. The postgres image docs say this lets you upgrade between major versions with the faster --link mode of pg_upgrade.

Docker Desktop’s Stored data tab for the staging database volume, with PostgreSQL’s files inside a folder named 18, then docker.

The staging database volume from Step 10, in Docker Desktop’s Volumes view.

Why do I get a 400 Bad Request with nothing in the logs?

The Host header isn’t in ALLOWED_HOSTS, usually because you opened the app by its IP address. With DEBUG off, Django’s default logging keeps quiet about it. All I got was this line from Gunicorn’s access log.

web-1  | 192.168.65.1 - - [13/Oct/2026:10:50:00 +0000] "GET / HTTP/1.1" 400 143 "-" "curl/8.7.1"

Add the address, for example ALLOWED_HOSTS=localhost,127.0.0.1,192.168.1.50, and run docker compose up -d so Compose recreates the container with the new value.

Why does Gunicorn log “Control server error”?

web-1  | [2026-10-13 10:33:33 +0000] [1] [ERROR] Control server error: [Errno 13] Permission denied: '/nonexistent'

Gunicorn 25.1 and newer try to create a control socket in the user’s home folder, and a system user made with adduser --system has its home set to /nonexistent. The app still works. Add --no-control-socket to the Gunicorn command, as in the Dockerfile from Step 4, and the error goes away.

Why does Compose warn that “version is obsolete”?

Your compose file starts with a version: line copied from an older tutorial. Compose prints “the attribute version is obsolete, it will be ignored, please remove it to avoid potential confusion.” Delete the line.

What should you check before production?

Run Django’s deployment check inside the container. This is what it said about the demo.

$ docker compose exec web 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.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems.
?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your site should be available over both SSL and non-SSL connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS.
?: (security.W012) SESSION_COOKIE_SECURE is not set to True. Using a secure-only session cookie makes it more difficult for network traffic sniffers to hijack user sessions.
?: (security.W016) You have 'django.middleware.csrf.CsrfViewMiddleware' in your MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. Using a secure-only CSRF cookie makes it more difficult for network traffic sniffers to steal the CSRF token.

System check identified 5 issues (0 silenced).

The error is new in Django 6.1. startproject now writes a MAILERS setting with the console email backend, and the deploy check refuses it. Set up a real email backend before launch.

The warnings are about HTTPS, so they go away once a proxy terminates HTTPS in front of Django and you turn those settings on. Work through the rest of this list too.

  • DEBUG is false and SECRET_KEY is long, random and secret.
  • ALLOWED_HOSTS lists only your real hostnames, and CSRF_TRUSTED_ORIGINS has your https:// address.
  • HTTPS ends at a reverse proxy or load balancer, with SECURE_PROXY_SSL_HEADER set so Django knows the request was secure. Then turn on SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE and HSTS. The deployment checklist explains each one.
  • The database port isn’t published. The db service in Step 7 has no ports: entry, so only the web container can reach it. Keep it that way.
  • Backups run on a schedule, and you’ve tested a restore.
  • User uploads go to a volume or to object storage such as S3, never only inside the container.
  • You rebuild the image regularly to pick up security fixes in the base image.

Running Django in Docker doesn’t make an app production-ready. It makes the environment predictable, and everything on that list is easier to get right when the environment holds still.

What’s the one thing on your server that still doesn’t match your laptop, and how long has it been “temporary”?