Skip to content
Visual explainer 4h to learn 5 steps

Dockerfiles & multi-stage builds for Python

Write a small, cache-friendly image for your FastAPI service.

By Invicly Tech, , in Full DevOps with Python. About 13 minutes to read.

Topic 14 of 34

In short

A Dockerfile is the recipe for your image. Ordering layers for caching, using a slim base, a multi-stage build and a non-root user gives a small, fast and safer image.

Explained simply

A Dockerfile is a text file with step-by-step instructions for building an image. Each line starts with a keyword: FROM picks the starting image, COPY puts files in, RUN runs a command, and CMD says what to start when a container runs.

Docker remembers the result of each step. If a step and everything before it did not change, Docker reuses the saved result instead of running it again. That is why you install your Python packages before you copy your code: code changes often, packages change rarely.

A multi-stage build uses two or more FROM lines in one file. You install and compile things in the first stage, then copy only the finished result into a clean final stage. Tools you needed only for building stay behind, so the final image is smaller.

Small images download faster, start faster, and contain fewer programs that could have security holes. Using a slim base image, skipping caches, and leaving out test files all help.

By default, the program inside runs as root. Adding a normal user and switching to it with USER means that if someone breaks into your app, they have far fewer powers.

Press Play on a diagram to walk through it one step at a time.

CompareSingle-stage vs multi-stage
Single-stage
  • Build tools stay in image
  • Often several hundred MB
  • More packages to patch
  • Simple to write
Multi-stage
  • Build in one stage
  • Copy only results to final
  • Small slim runtime image
  • Smaller attack surface
MapWhere the bytes in a Python image come from
Final image
  • Base image
    • Debian slim files
    • Python interpreter
    • Usually the largest part
  • Runtime libraries
    • libpq5 for Postgres
    • Only what imports need
  • Virtual environment
    • Your pip packages
    • Copied from the build stage
  • App code
    • Small, changes often
    • Filtered by .dockerignore
  • Left out on purpose
    • Compilers and headers
    • pip cache
    • .git and tests

In depth

The instructions you will actually use

FROM sets the base image. WORKDIR sets the folder for later steps and creates it if needed. COPY copies files from the build context; ADD can also unpack tar files and fetch URLs, but COPY is clearer and preferred. RUN executes a command and saves the result as a layer.

ENV sets environment variables that stay in the image and in running containers. ARG sets build-time variables that do not exist at runtime, passed with docker build --build-arg. Never pass secrets through ARG or ENV, because they are visible in docker history and docker inspect.

CMD gives the default command, and ENTRYPOINT gives the fixed program. With both, CMD becomes the default arguments to ENTRYPOINT. Arguments after the image name in docker run replace CMD only. EXPOSE documents the port but publishes nothing; you still need -p.

Two env vars are common for Python: PYTHONUNBUFFERED=1 so logs appear at once in docker logs, and PYTHONDONTWRITEBYTECODE=1 so no .pyc files are written.

CompareShell form vs exec form
Shell form
  • CMD uvicorn main:app
  • Runs through /bin/sh -c
  • Shell is PID 1 and may not forward SIGTERM
  • Variables like $PORT are expanded
Exec form
  • CMD ["uvicorn", "main:app"]
  • Runs the program directly
  • Your app is PID 1 and gets signals
  • No shell, so no $VAR expansion

Making the build cache work for you

Docker checks each instruction in order. A RUN step is reused if the text of the command and the parent layer are the same. A COPY step is reused only if the copied files have the same checksums. Once one step misses the cache, every step after it runs again.

So order steps from least to most often changed: system packages, then requirements.txt and pip install, then your source code. Put cleanup in the same RUN as the install, for example apt-get update and apt-get install followed by rm -rf /var/lib/apt/lists/* in one line, because a later step cannot make an earlier layer smaller.

BuildKit, the default builder since Docker 23, adds cache mounts. RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt keeps pip's download cache between builds without putting it in the image, so even a changed requirements file installs faster.

The build context is everything in the folder you pass to docker build. A .dockerignore with .git, .venv, __pycache__ and .env keeps it small and avoids cache misses caused by unrelated files.

Multi-stage builds step by step

Each FROM starts a new stage, and you can name it with AS. Only the last stage becomes the image, unless you choose another with docker build --target. COPY --from=build copies files out of an earlier stage.

For Python, the usual pattern is: in the build stage, install any compilers or headers you need (for example build-essential and libpq-dev for a package that compiles C code), create a virtual environment, and pip install into it. In the final stage, start again from the slim base, install only the runtime libraries (such as libpq5), and copy the whole venv across. Because the venv lives at the same path in both stages, its scripts keep working.

An alternative is to build wheels in stage one with pip wheel -w /wheels, then pip install --no-index --find-links /wheels in the final stage. Stages that the final stage does not depend on are skipped by BuildKit, and independent stages can build in parallel.

FlowWhat travels between stages
  1. 1
    Stage build

    python:3.12-slim plus compilers

  2. 2
    Create /venv

    pip install requirements into it

  3. 3
    Stage final

    Fresh python:3.12-slim, runtime libs only

  4. 4
    COPY --from=build

    Bring over /venv and nothing else

  5. 5
    COPY app code

    Add source, set USER, set CMD

Choosing a base image

The full python:3.12 image is based on Debian with many build tools and is around 1 GB. python:3.12-slim is the same Debian with most extras removed and is roughly 150 MB, which suits most web services.

python:3.12-alpine is smaller still, but Alpine uses the musl C library instead of glibc. Many Python wheels are built for glibc, so pip may have to compile packages from source, which makes builds slow and sometimes fails. Small size is rarely worth that pain for Python.

Distroless images contain only the runtime with no shell or package manager, which shrinks the attack surface but makes debugging harder.

Whatever you choose, pin it. python:3.12-slim moves when new patch versions come out; python:3.12.7-slim-bookworm is more precise; adding @sha256 with a digest pins it exactly. Rebuild regularly anyway, so you pick up security fixes in the base. A scanner such as Trivy or docker scout lists known vulnerabilities in an image.

  • Debian slim: best default for Python
  • Alpine: small, but musl can break or slow wheels
  • Distroless: smallest attack surface, no shell

Running as non-root and other hardening

If you do not set USER, the process runs as root inside the container. Root in a container is limited by namespaces, but a kernel bug or a bad mount can turn it into real damage on the host. Create a user and switch to it near the end of the Dockerfile.

Use a numeric ID, such as USER 10001, or make sure the user name maps to a fixed ID. Kubernetes with runAsNonRoot can only verify a numeric user. Copy code with COPY --chown so the app user owns it, but keep the code read-only if the app does not need to write.

A non-root user cannot bind ports below 1024 by default, so listen on 8000 or 8080 and map ports outside. Add a HEALTHCHECK if you run plain Docker or Compose; Kubernetes ignores it and uses its own probes.

Keep secrets out of layers: use RUN --mount=type=secret,id=pip_token to read a private index token during the build without saving it in the image.

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Write a Dockerfile for the FastAPI app~50m
  2. 2
    Order layers for cache hits~50m
  3. 3
    Add a multi-stage build~50m
  4. 4
    Run as a non-root user~50m
  5. 5
    Shrink the image with a slim base~50m

Key points

  • Copy requirements.txt and install before copying code to keep the install layer cached.
  • python:3.12-slim is far smaller than the full image and works for most apps.
  • Run as a non-root user so a compromised app has fewer powers.
  • A .dockerignore keeps .git, .venv and secrets out of the build context.

Key terms

Tap a card to flip it. 0/4 known

Examples

dockerfile
FROM python:3.12-slim AS build
WORKDIR /app
RUN python -m venv /venv
COPY requirements.txt .
RUN /venv/bin/pip install --no-cache-dir -r requirements.txt

FROM python:3.12-slim
RUN useradd --create-home app
COPY --from=build /venv /venv
WORKDIR /app
COPY --chown=app . .
USER app
ENV PATH="/venv/bin:$PATH"
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Build a venv in stage one, copy it into a clean slim image.

A production-style Dockerfile for a FastAPI app with Postgres

The app uses psycopg built from source, which needs a C compiler and libpq headers to build but only libpq5 to run. Step 1: the build stage installs the compiler, makes a venv and installs requirements with a pip cache mount. Step 2: the final stage starts clean, installs only libpq5 and cleans apt lists in the same RUN. Step 3: it creates a user with a fixed ID, copies the venv and code, and runs uvicorn in exec form. Build it with docker build -t api:dev . and check the size with docker images.

dockerfile
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS build
RUN apt-get update && apt-get install -y --no-install-recommends build-essential libpq-dev && rm -rf /var/lib/apt/lists/*
RUN python -m venv /venv
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip /venv/bin/pip install -r requirements.txt

FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PATH="/venv/bin:$PATH"
RUN apt-get update && apt-get install -y --no-install-recommends libpq5 && rm -rf /var/lib/apt/lists/*
RUN useradd --uid 10001 --create-home app
COPY --from=build /venv /venv
WORKDIR /app
COPY --chown=10001 . .
USER 10001
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Find out why every build reinstalls all packages

Builds take three minutes even for a one-line change. Step 1: look at the build output; steps marked CACHED were reused, and the first one without it is where the cache broke. Step 2: you find COPY . . before pip install, so any code change invalidates the install. Step 3: move COPY requirements.txt and pip install above COPY . . Step 4: you also notice .git is in the context, so every commit changes it; add a .dockerignore. Step 5: rebuild twice and edit main.py in between; now only the final COPY runs.

bash
cat > .dockerignore <<'EOF'
.git
.venv
__pycache__
*.pyc
.env
tests/
EOF
docker build --progress=plain -t api:dev . 2>&1 | grep -E "CACHED|RUN|COPY"
echo "# tweak" >> main.py
docker build -t api:dev .        # pip install step now shows CACHED
docker history api:dev

Quick reference

  • Order: base, system packages, requirements.txt, pip install, then COPY . . last
  • Clean apt lists in the same RUN as apt-get install, or the space stays in the image
  • Use exec form CMD ["uvicorn", ...] so your app is PID 1 and receives SIGTERM
  • ENV PYTHONUNBUFFERED=1 makes print and logging output show up in docker logs at once
  • docker build --target build -t api:build . builds only up to the named stage
  • RUN --mount=type=cache,target=/root/.cache/pip keeps the pip cache out of the image
  • USER 10001 (numeric) lets Kubernetes runAsNonRoot verify the user
  • EXPOSE only documents a port; you still publish it with -p at run time

Common mistakes

  • COPY . . before installing dependencies, so every code change reinstalls everything.
  • No .dockerignore, which copies .env files and secrets into the image.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Your Dockerfile has COPY . . before RUN pip install -r requirements.txt. What happens when you edit one Python file?

Question 2

2What is the difference between ARG and ENV?

Question 3

3Why is python:3.12-alpine often a poor choice for Python apps?

Question 4

4You run docker run api:dev python manage.py check. Which instruction does the extra command replace?

Question 5

5In a multi-stage build, how do you get the venv from the build stage into the final image?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a .dockerignore for a Python project and show that the build context got smaller.

  2. Exercise 2medium

    Build the same app twice, once FROM python:3.12 single-stage and once with the multi-stage slim Dockerfile, and compare the sizes.

  3. Exercise 3hard

    Prove your image runs as non-root and stops quickly. Check the user ID, then time docker stop.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use CMD or ENTRYPOINT?
Use CMD for a normal app so people can easily override the command. Use ENTRYPOINT when the image is a single tool and arguments should always go to it, often combined with CMD for default arguments.
Do I need a virtual environment inside a Docker image?
It is not required, but a venv makes multi-stage builds easy because you copy one folder, and it keeps your packages separate from the system Python.
How do I make my Docker image smaller?
Use a slim base, a multi-stage build, --no-cache-dir or a cache mount for pip, a .dockerignore, and clean up in the same RUN step that created the files.
How do I pass a secret during docker build?
Use BuildKit secrets: docker build --secret id=token,src=token.txt with RUN --mount=type=secret,id=token in the Dockerfile. Never use ARG or ENV for secrets.

Go deeper

ShareXLinkedInWhatsApp