Production-Grade Multi-Stage Dockerfile for Django & Gunicorn
Turn a Django application into an image that starts fast, runs as a non-root user, and carries no build tooling.
- Time
- 31 min
- Level
- Beginner
- Objectives
- 4 objectives
- Cost
- Free
Where this fits in the platform
Already built
This lab adds
- A small, non-root container image of the application
The scenario#
The image is 950 MB, ships gcc to production, and runs as root. It also takes four minutes to rebuild after a one-line code change, because every build reinstalls every dependency.
All three problems have the same fix, and it is the order of the instructions rather than any single one of them.
Hands-on environment
Run this lab in a real terminal, free and in your browser. The environment is temporary and yours alone — break it as much as you like.
Open the terminalOpens in Killercoda, in a new tab — keep this page open for the steps.
Run it on your own machine
Run this lab on your own machine. One command starts the environment, with everything the lab needs already installed:
You will need:
- docker
git clone https://github.com/EgyKode/EgyKode-lab.git
cd EgyKode-lab
./egykode start
./egykode shellYou need Docker and Git installed. Everything else runs inside the environment. The first start downloads it and takes a few minutes; later starts are seconds.
Not sure what you already have? Run: npm run doctor — it checks and changes nothing.
Anything you tick here is your own record. EgyKode cannot see inside that terminal, so the success criteria stay self-assessed even when the environment checks your work for you.
The Dockerfile
Step 1 of 4
What you are building#
A multi-stage build uses several FROM instructions in one Dockerfile.
Only the last stage becomes the image; the earlier ones are scratch space that
is discarded.
STAGE 1 — builder STAGE 2 — runtime
python:3.13-slim python:3.13-slim
+ gcc, make, libpq-dev copies ONLY the compiled wheels
+ compiles wheels ══════▶ no compiler, no headers
~950 MB, thrown away runs as UID 10001
~160 MB, shippedThree things this buys you, and the second is the one that matters most:
- Size. ~950 MB to ~160 MB, so pulls are faster on every node.
- Attack surface. An attacker who reaches a container with
gccin it can compile an exploit there. One without cannot. - Honesty. If the runtime stage is missing a library, the build fails on your machine rather than the container failing in production.
Build it#
What you are proving: You can write a multi-stage build whose final image carries no compiler or build toolchain
Marking this settles success criterion 1.
# ---------- Stage 1: build ----------
FROM python:3.13-slim AS builder
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential libpq-dev && rm -rf /var/lib/apt/lists/*
WORKDIR /build
COPY requirements.txt .
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt
# ---------- Stage 2: runtime ----------
FROM python:3.13-slim AS runtime
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
RUN apt-get update && apt-get install -y --no-install-recommends \
libpq5 && rm -rf /var/lib/apt/lists/* \
&& useradd --uid 10001 --create-home --shell /usr/sbin/nologin appuser
WORKDIR /app
# Dependencies first, and in their own layer — see step 2.
COPY --from=builder /wheels /wheels
COPY requirements.txt .
RUN pip install --no-cache-dir --no-index --find-links=/wheels -r requirements.txt \
&& rm -rf /wheels
# Application code last, because it changes on every commit.
COPY --chown=appuser:appuser . .
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=20s \
CMD python -c "import urllib.request,sys; \
sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz').status==200 else 1)"
ENTRYPOINT ["./entrypoint.sh"]
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "3", "app.wsgi:application"]libpq-dev is in the builder and libpq5 in the runtime. The -dev package
carries headers needed to compile the driver; the runtime needs only the
shared library. Copying that distinction wholesale is what keeps the second
stage small.
What you are proving: You can order layers so that changing application code does not reinstall dependencies
Marking this settles success criterion 3.
COPY requirements.txt . # changes rarely
RUN pip install ... # cached until requirements.txt changes
COPY . . # changes every commitDocker caches each layer and invalidates everything after the first change. Put
COPY . . before the install and every code change reinstalls every
dependency — the four-minute rebuild. In this order, a code change reuses the
dependency layer and rebuilds in seconds.
Verify the cache is working:
docker build -t app:1.0 .
echo "# touch" >> app/views.py
docker build -t app:1.1 . # look for "CACHED" on the pip layerWhat you are proving: You can make a container wait for its database instead of crash-looping against it
Marking this settles success criterion 4.
#!/bin/sh
set -e
echo "waiting for ${DB_HOST}:${DB_PORT:-5432}"
until nc -z "${DB_HOST}" "${DB_PORT:-5432}"; do
sleep 1
done
python manage.py migrate --noinput
exec "$@"exec "$@" is the important line. Without exec, the shell stays as PID 1 and
Gunicorn runs as its child — so docker stop sends SIGTERM to the shell,
which does not forward it, and the container is killed 10 seconds later after
dropping in-flight requests. With exec, Gunicorn becomes PID 1 and shuts
down gracefully.
What you are proving: You can measure the image you built and prove it runs as a non-root user
Marking this settles success criterion 2.
docker build -t app:1.0 .
docker images app:1.0 --format '{{.Size}}'
docker history app:1.0 | headVerify it worked#
# Non-root, with the UID you chose
docker run --rm app:1.0 id
# uid=10001(appuser) gid=10001(appuser)
# No compiler in the shipped image
docker run --rm app:1.0 sh -c 'which gcc || echo "no compiler — correct"'
# Under 200 MB
docker images app:1.0 --format '{{.Size}}'
# The health check is wired up
docker run -d --name app -p 8000:8000 app:1.0
docker inspect --format '{{.State.Health.Status}}' appEach of those checks an outcome. docker images showing the tag exists would
prove only that a build ran.
pip install fails in the runtime stage with a missing header
You installed a -dev package only in the builder and the wheel is being
compiled again. That means it was not built in stage 1 — check the
--find-links path and that --no-index is set, so pip cannot silently reach
the internet and rebuild.
Permission denied writing a file at runtime
USER appuser cannot write to directories owned by root. COPY --chown fixes
the application directory; anything else the app writes needs an explicit
RUN mkdir -p /app/media && chown appuser /app/media.
Every build reinstalls dependencies
COPY . . appears before the install. Move it after, and check .dockerignore
excludes .git — a changing .git directory invalidates the cache on every
build even when no source file changed.
docker stop takes exactly 10 seconds
The entrypoint is missing exec, so SIGTERM reaches a shell that ignores it
and Docker falls back to SIGKILL after the grace period.
Health check never turns healthy
The command runs inside the container, so anything it calls must exist there.
docker inspect --format '{{json .State.Health}}' app | jq shows the actual
output of the last few probes.
Clean up#
docker rm -f app
docker rmi app:1.0 app:1.1
docker builder prune -fCost of this lab: Free — everything runs locally.
Maintained by others, on Killercoda. Useful for extra repetition on one tool — it does not complete this lab or settle any criterion above.
Success criteria
0 of 4
The concept behind it
Next up
Lab 9 of 59 on the project path