Shrink Python Docker Images: Multi-Stage, Slim, Distroless and uv

,
Shrink Python Docker Images: Multi-Stage, Slim, Distroless and uv

A “hello world” FastAPI service built on python:3.12 can easily produce an image of around a gigabyte. Most of that is a compiler toolchain, apt caches, pip caches and build dependencies that the running app never touches. This guide shrinks a Python Docker image step by step: switch to a slim base, use a multi-stage build, install with uv using cache mounts, copy only the virtual environment into the final stage, and optionally go distroless. Each step says what it removes and what it can break.

Quick fix: Build in a python:3.x-slim stage with uv sync --locked --no-editable, then COPY --from=builder /app/.venv /app/.venv into a fresh slim image. Add a .dockerignore. That alone usually removes most of the bloat.

The Dockerfiles below follow uv’s official Docker integration guide (uv 0.13.x era) and Docker’s own best-practice docs. Image sizes vary with your dependencies, so measure your own with docker images instead of trusting anyone’s headline number, including ours.

Why are Python Docker images so big?

Source of bloat Typical cause Fix
Base image Full python:3.x (Debian + build tools) python:3.x-slim or distroless
Build toolchain gcc, headers for compiling wheels Install them only in a builder stage
Package caches pip/uv cache baked into a layer Cache mounts, not layers
Source and junk .git, tests, .venv, notebooks copied in .dockerignore
Dev dependencies pytest, linters in prod image uv sync --no-dev / UV_NO_DEV=1
Bytecode Generated at runtime, not a big size issue UV_COMPILE_BYTECODE=1 for faster startup

What does a good multi-stage build look like?

The idea: the builder stage has uv and anything needed to compile. The runtime stage receives only the finished virtual environment.

Multi-stage Python Docker build with uv: builder stage syncs the venv, runtime stage copies only .venv
Builder stage vs runtime stage: only .venv crosses the boundary (diagram made with D2).

Step 1: Add a .dockerignore

.git
.venv
__pycache__/
*.pyc
.pytest_cache/
tests/
docs/
*.ipynb
.env

The “transferring context” size in docker build output drops noticeably if you had a local .venv or a large .git. Excluding .venv matters for correctness too. A host venv copied into a Linux image will often be broken.

Step 2: Write the multi-stage Dockerfile

This follows the non-editable pattern from uv’s docs, with the bytecode and link-mode settings the guide recommends:

# syntax=docker/dockerfile:1
FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:0.13.7 /uv /uvx /bin/

ENV UV_COMPILE_BYTECODE=1 \
    UV_LINK_MODE=copy \
    UV_PYTHON_DOWNLOADS=0 \
    UV_NO_DEV=1

WORKDIR /app

# 1) dependencies only: cached until uv.lock changes
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --locked --no-install-project --no-editable

# 2) the project itself
COPY . /app
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --locked --no-editable

FROM python:3.12-slim
RUN useradd --create-home --uid 10001 app
COPY --from=builder --chown=app:app /app/.venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH"
USER app
# your project's console script (keep this comment on its own line)
CMD ["hello"]

What each piece does:

  • Pinned uv tag (0.13.7): reproducible builds. uv’s docs also show pinning by @sha256: digest.
  • UV_PYTHON_DOWNLOADS=0: use the image’s Python so both stages share the same interpreter path. Otherwise the copied venv points at a Python that doesn’t exist in the runtime stage.
  • UV_LINK_MODE=copy: the cache is a mount on a different filesystem, so hard links can’t work; this silences the warning.
  • Cache mount: the uv cache speeds up rebuilds but never lands in an image layer.
  • Two syncs: dependencies change less often than your code, so step 1 stays cached across most commits.
  • --no-editable: the project is installed into the venv as a real package. The runtime stage doesn’t need /app/src at all.

Step 3: Build and compare

docker build -t myapp:slim .
docker images myapp
docker run --rm myapp:slim

Here is what that comparison looked like for a small project created with uv init --package hello that depends on requests and rich. All three images were built with Docker 26.1.5 on Debian 13:

ImageHow it was builtSize
myapp:naiveSingle stage, FROM python:3.12, pip install .1.13 GB
myapp:slim-pipSingle stage, FROM python:3.12-slim, pip144 MB
myapp:slimThe multi-stage uv Dockerfile above134 MB

Most of the win comes from the slim base image, not from uv. The multi-stage build saves a further 10 MB because no pip, build tooling, or uv binary reaches the runtime stage, and it caches the dependency layer so rebuilds after a code change are fast. docker history myapp:slim put the copied .venv at 14.7 MB, which means the remaining weight is the Python base image itself.

Terminal output comparing Python Docker images: naive 1.13 GB, slim with pip 144 MB, uv multi-stage 134 MB, plus the /bin/sh [hello] not found error from an inline CMD comment and the fixed run printing Hello from hello
Real run: Docker 26.1.5, uv 0.13.9, python:3.12-slim (Python 3.12.16 inside the image).

What I ran into

The first build ran, but the container failed with /bin/sh: 1: [hello]: not found. The cause was a trailing comment on the CMD line. Docker only treats CMD as exec form when the whole argument is a valid JSON array. A comment after the closing bracket makes it a shell-form string, so /bin/sh tried to run a program literally named [hello]. Moving the comment to its own line fixed it, and the container printed Hello from hello!. Running id inside it confirmed uid=10001(app), so the non-root user took effect.

What if a dependency needs a compiler?

Packages without wheels for your platform (or with --no-binary) compile during uv sync. Install the toolchain in the builder only:

FROM python:3.12-slim AS builder
RUN apt-get update \
 && apt-get install -y --no-install-recommends build-essential \
 && rm -rf /var/lib/apt/lists/*

The runtime stage stays clean. But if a compiled extension links against a shared system library (for example libpq for some PostgreSQL drivers), install the runtime library package in the final stage, or you’ll see ImportError: libpq.so.5: cannot open shared object file.

Should you go distroless?

Google’s distroless Python image (gcr.io/distroless/python3-debian…) has no shell, no package manager and no pip. That shrinks the attack surface and usually the size too. The trade-offs:

slim distroless
Shell for debugging Yes No (a :debug variant has busybox)
apt-get in final image Yes No
Python version You choose (3.12, 3.13, …) Whatever Debian ships for that distroless release
Venv compatibility Same base as builder Builder must match its Python minor version and path

The last row is the classic failure. A venv’s bin/python is a symlink to the interpreter it was created with. If the builder used /usr/local/bin/python3.12 (the official image) and distroless has /usr/bin/python3.13, the venv breaks with exec: no such file or directory. The fix is to build in an image whose Python matches distroless exactly, for example a Debian builder using Debian’s own python3, and to check the distroless tag’s Python version before pinning it. If you can’t keep them in sync, slim is the pragmatic choice.

Tip: Alpine (python:3.x-alpine) looks attractive by size, but it uses musl. Many scientific packages then need musllinux wheels or a source build, which can make builds slower and images bigger. Measure before switching.

Can you skip copying uv into the image?

Yes. uv’s docs show mounting the binary only for the RUN that needs it:

RUN --mount=from=ghcr.io/astral-sh/uv:0.13.7,source=/uv,target=/bin/uv \
    uv sync --locked --no-editable

In a multi-stage build this matters less, because uv only exists in the builder anyway.

How do you find what’s still taking up space?

Guessing wastes time, so measure layer by layer:

docker history --no-trunc --format '{{.Size}}\t{{.CreatedBy}}' myapp:slim | head
docker run --rm --entrypoint sh myapp:slim -c 'du -sh /app/.venv/lib/python*/site-packages/* | sort -h | tail'

The first command lists layers with the instruction that created each one. The second (slim images only, since distroless has no sh) shows the largest installed packages. The heaviest dependencies end up at the bottom of the list. In the test image, that was pygments at 9.4 MB, ahead of rich at 2.9 MB and urllib3 at 1.1 MB. If a package you don’t recognize shows up there, uv tree --invert --package <name> run locally tells you which dependency pulled it in. For pygments it printed pygments v2.21.0 under rich v15.0.0 under hello v0.1.0, so rich is the reason it ships. Open-source layer explorers such as dive show the same data interactively, if you prefer a UI.

Common findings: a CUDA build of PyTorch where the CPU build would do, test data shipped inside a package, or a dev dependency that leaked into the main group because it was added without --dev.

Troubleshooting

“error: The lockfile at uv.lock needs to be updated”

--locked refuses to build if pyproject.toml and uv.lock disagree. Run uv lock locally and commit the result. This check is a feature: it stops builds from silently resolving different versions than CI.

“No interpreter found” or the venv runs the wrong Python

Set UV_PYTHON_DOWNLOADS=0 and use the same base image tag in both stages.

Permission denied at runtime

You copied files owned by root and switched to a non-root user. Use COPY --chown= as shown above.

FAQ

Is pip install --no-cache-dir still needed?

Not with uv and a cache mount. The cache never becomes part of a layer.

Does UV_COMPILE_BYTECODE make images bigger?

Slightly, because .pyc files are added. In exchange the container skips compiling on first import, which helps startup time. For most services the trade is worth it.

Should I use the ghcr.io/astral-sh/uv:python3.12-trixie-slim images?

They’re convenient for the builder stage. uv publishes derived images with Python preinstalled. Keep the runtime stage on the plain Python image you trust.

Related guides

Leave a Reply