Skip to content

Multi-stage Docker builds — small images, clean separation

Use multi-stage Dockerfiles to keep build dependencies out of runtime images. Patterns for compiled languages, package managers, and shared layers across services.

A single-stage Dockerfile that installs Go, builds a binary, and runs it ships an image with the full Go toolchain in it — gigabytes of compilers that the runtime will never use. Multi-stage builds split that into a builder stage that has the toolchain and a runtime stage that only has the binary. The same image goes from 1.2 GB to 25 MB, the attack surface drops accordingly, and the build cache layers still work correctly.

How to verify

Compare a single-stage image to a multi-stage equivalent for the same code:

docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}" | head
docker history <image> --no-trunc --format "table {{.CreatedBy}}\t{{.Size}}"

# What's actually in the runtime image?
docker run --rm <image> sh -c "find / -name '*.go' 2>/dev/null | head"
docker run --rm <image> which go npm pip make gcc 2>&1 | head

If which gcc returns a path in your runtime image, the build toolchain is along for the ride and shouldn’t be.

What’s happening

FROM can appear multiple times in a single Dockerfile. Each FROM starts a new stage with its own layer cache and filesystem. COPY --from=<stage> reaches into a previous stage’s filesystem and copies files into the current one. The final image is whatever the last FROM produces; earlier stages exist only during the build.

The pattern works because the things you need to build software (compilers, package managers, headers, source code) are not the things you need to run it (the compiled binary, a small runtime, maybe a TLS cert bundle). Separating them gives you all the benefits of a powerful build environment without dragging it into production.

The procedure

A Go web service — single-stage on the left, multi-stage on the right (conceptually):

# Stage 1: builder
FROM golang:1.22-bookworm AS builder
WORKDIR /src

# Cache module downloads independently from source changes
COPY go.mod go.sum ./
RUN go mod download

COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
    go build -ldflags="-s -w" -o /out/app ./cmd/server

# Stage 2: runtime
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=builder /out/app /app
EXPOSE 8080
USER nonroot:nonroot
ENTRYPOINT ["/app"]

Distroless contains nothing except the bare libraries the binary needs — no shell, no package manager, no debug tools. The image is around 20 MB and contains exactly your binary plus the CA bundle.

For a Node.js application:

FROM node:20-bookworm-slim AS builder
WORKDIR /build
COPY package.json package-lock.json ./
RUN npm ci --include=dev
COPY . .
RUN npm run build && npm prune --omit=dev

FROM node:20-bookworm-slim AS runtime
WORKDIR /app
COPY --from=builder /build/node_modules ./node_modules
COPY --from=builder /build/dist ./dist
COPY --from=builder /build/package.json ./
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]

The builder stage has dev dependencies (TypeScript, bundlers, test runners). The runtime stage gets only the production node_modules and the compiled output.

For a Python web service with native dependencies:

FROM python:3.12-slim-bookworm 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 install --user --no-cache-dir -r requirements.txt

FROM python:3.12-slim-bookworm AS runtime
RUN apt-get update && apt-get install -y --no-install-recommends \
      libpq5 \
 && rm -rf /var/lib/apt/lists/*
COPY --from=builder /root/.local /home/app/.local
WORKDIR /app
COPY src/ ./src/
RUN useradd --system --uid 1000 app && chown -R app:app /home/app
USER 1000:1000
ENV PATH=/home/app/.local/bin:$PATH
EXPOSE 8080
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]

The builder has build-essential and libpq-dev (headers) so psycopg2 can compile against libpq. The runtime has only libpq5 — the shared library at run time, no headers, no compilers.

Build a specific stage when you want to debug:

# Build only the builder stage (useful for shelling in and inspecting)
docker build --target builder -t myapp:builder .

# Standard build picks up the last stage
docker build -t myapp:latest .

# With BuildKit, parallel stages build concurrently
DOCKER_BUILDKIT=1 docker build -t myapp:latest .

When you have several services sharing a base layer, factor it out:

FROM python:3.12-slim-bookworm AS base
RUN apt-get update && apt-get install -y --no-install-recommends \
      libpq5 ca-certificates \
 && rm -rf /var/lib/apt/lists/*
RUN useradd --system --uid 1000 app
USER 1000:1000
WORKDIR /app

FROM base AS api
COPY --from=builder /root/.local /home/app/.local
COPY src/api/ ./
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]

FROM base AS worker
COPY --from=builder /root/.local /home/app/.local
COPY src/worker/ ./
CMD ["python", "worker.py"]

Two images from one Dockerfile, sharing the base. Built via docker build --target api -t app:api and docker build --target worker -t app:worker.

Common pitfalls

  • Using a different base image for builder and runtime that doesn’t have matching glibc versions — the compiled binary will fail to load shared libraries at runtime. Pin both to the same Debian/Ubuntu release.
  • Copying the wrong path from the builder stage (COPY --from=builder /app /app when the binary is at /build/out/app) — caught at runtime, not build time, because the COPY succeeds silently.
  • Forgetting that WORKDIR resets between stages — each stage has its own working directory.
  • Building with CGO enabled when targeting distroless static — distroless static has no libc, so any binary that dynamically links will fail. Use CGO_ENABLED=0 for Go, or target distroless/cc-debian12 if dynamic linking is required.
  • Not using --mount=type=cache for package manager caches in BuildKit, rebuilding all dependencies on every layer invalidation. See BuildKit cache mounts.

We ship every client service as a multi-stage build with a distroless or minimal runtime. The pattern is part of our managed operations playbook — the build is the artifact, not the dev environment.