Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Distribution and Docker

Docker Images for Python Applications

Build small, fast, secure Docker images for Python applications. Layer caching, multi-stage builds, non-root users, uv and pip installs, plus a Dockerfile linter and cache simulator.

A library is distributed as a wheel on PyPI. An application (a web service, a worker, a scheduled job) is usually distributed as a container image: your code, the Python interpreter, system libraries and all dependencies in one bundle that runs the same everywhere. A good image is small, builds quickly when only your code changed, and does not run as root.

This lesson shows how to write that Dockerfile for a Python project, using ideas from everything earlier in this course (lock files especially). Docker cannot run inside this web page, so Dockerfiles are shown as read-only code. To make the ideas hands-on, the runnable examples simulate layer caching and lint a Dockerfile with real Python code.

A basic Dockerfile

DOCKERFILE
FROM python:3.13-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["python", "-m", "myapp"]

Line by line:

  • FROM python:3.13-slim picks a base image. slim is a Debian-based image without compilers and documentation, much smaller than the full image.
  • WORKDIR /app sets the directory for the following commands.
  • COPY requirements.txt . and RUN pip install install dependencies. --no-cache-dir stops pip from saving downloads inside the image.
  • COPY . . copies the rest of your code last.
  • CMD is the command that runs when the container starts. Use the exec form (a JSON list) so signals such as SIGTERM reach your process and it can shut down cleanly.

Layer caching: order matters

Every instruction creates a layer. Docker reuses a layer from cache if the instruction and everything before it are unchanged. The moment one layer changes, all the layers after it are rebuilt. That is why dependencies are installed before copying the code: your code changes on every commit, your dependencies rarely do.

flowchart TD
    A["FROM python:3.13-slim"] --> B["COPY requirements.txt"]
    B --> C["RUN pip install"]
    C --> D["COPY . ."]
    D --> E["CMD"]
    X["code edited"] -.invalidates.-> D
    Y["requirements.txt edited"] -.invalidates.-> B

Editing code rebuilds only from COPY . .; editing requirements rebuilds from the first COPY.

The simulator below chains a hash through each layer the way Docker's cache key works, so you can see what gets rebuilt:

Python Simulate Docker layer caching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the first ordering, editing any file invalidates the early COPY . ., so the slow pip install runs again on every change. In the second ordering, only the last layer is rebuilt. On a project with large dependencies, that difference is minutes versus seconds.

Environment settings worth adding

DOCKERFILE
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1
  • PYTHONUNBUFFERED=1 sends print output and logs straight to the container log instead of holding them in a buffer.
  • PYTHONDONTWRITEBYTECODE=1 skips .pyc files, keeping the image a little smaller.

Multi-stage builds with uv

Compilers and build tools are needed to install some packages, but not to run them. A multi-stage build installs everything in a builder stage and copies only the finished virtual environment into a clean final image:

DOCKERFILE
# ---- build stage ----
FROM python:3.13-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
WORKDIR /app

# 1. dependencies only (cached until the lock changes)
COPY pyproject.toml uv.lock ./
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-install-project --no-dev

# 2. the project itself
COPY src ./src
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-dev

# ---- runtime stage ----
FROM python:3.13-slim
RUN useradd --create-home --uid 1000 app
WORKDIR /app
COPY --from=builder --chown=app:app /app/.venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH" PYTHONUNBUFFERED=1
USER app
EXPOSE 8000
CMD ["python", "-m", "myapp"]

What this achieves:

  • The dependency layer depends only on pyproject.toml and uv.lock, so it is cached until the lock file changes.
  • --frozen refuses to re-resolve, so the image contains exactly what you tested.
  • --no-dev leaves out dependency groups meant for development.
  • The final stage has no compilers, no uv, and no package caches.
  • The app runs as an unprivileged user (USER app), so a flaw in your code cannot trivially become root inside the container.

If you prefer pip, the same pattern works: build wheels in the first stage (pip wheel -r requirements.txt -w /wheels) and install them in the second with pip install --no-index --find-links /wheels.

Choosing a base image

Base Size Notes
python:3.13 large Full Debian with compilers, easiest for building
python:3.13-slim small Best default for most apps
python:3.13-alpine smallest Uses musl libc; many wheels are built for glibc, so installs may compile from source and be slower. Use with care
Distroless Python small, minimal No shell or package manager; very small attack surface but harder to debug

Pin the version (3.13-slim, or a digest for strict reproducibility) and rebuild regularly to receive base image security patches.

.dockerignore

Without a .dockerignore, COPY . . sends your virtual environment, Git history and secrets into the build. Create one:

TEXT
.git
.venv
__pycache__/
*.pyc
.env
.pytest_cache
.mypy_cache
dist/
tests/

This also keeps the layer cache from being invalidated by irrelevant files.

A Dockerfile linter

Many of these rules are mechanical, so a script can check them. This stand-in reads a Dockerfile and reports violations; real tools such as hadolint do the same with a much larger rule set:

Python Lint a Dockerfile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Running and checking the image

Terminal
docker build -t myapp:1.0 .
docker run --rm -p 8000:8000 myapp:1.0
docker image ls myapp          # check the size
docker history myapp:1.0       # see the layers

Add a HEALTHCHECK or a readiness endpoint, keep configuration in environment variables (not baked into the image), and scan images for known vulnerabilities in CI. For Compose files, registries and security in depth, see the Docker tutorial on this site.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why copy requirements.txt (or the lock file) before copying the rest of the code?

    A layer is rebuilt when its inputs or any earlier layer change. Dependencies change rarely, so installing them before copying code preserves the cache.
  2. 2. What is the benefit of a multi-stage build?

    Build tools stay in the builder stage; the runtime stage copies in just the finished environment, making the image smaller and safer.
  3. 3. Why use the exec form CMD ["python", "app.py"]?

    The shell form runs your program as a child of /bin/sh, which may not forward signals.
  4. 4. Which base image tag is the best default for most Python apps?

    A pinned slim tag is small, reproducible and widely compatible with prebuilt wheels.

Summary

  • Applications ship as container images; use a pinned python:X.Y-slim base.
  • Order instructions from least to most frequently changing so the layer cache works.
  • Multi-stage builds, uv sync --frozen --no-dev and a non-root USER give small, reproducible, safer images.
  • Use .dockerignore, exec-form CMD, and environment variables for configuration; never bake in secrets.
  • Lint Dockerfiles and scan images in CI.

Next: Zipapps and Standalone Executables