Lesson 4 of 9 · 20m
Multi-Stage Builds: Compile Heavy, Ship Light
Build with a 1GB toolchain image, ship a 20MB runtime image — multi-stage builds are the highest-leverage Dockerfile technique there is.
The dirty secret of naive Dockerfiles: to compile a Go binary you need the Go toolchain (~800MB), but to run it you need nothing. Naive builds ship the compiler, the package cache, the test dependencies, and the CVEs that come with all of it. Multi-stage builds fix this by letting one Dockerfile have several FROM lines — each is a fresh stage, and you copy artifacts between stages, discarding the rest.
The canonical pattern
# syntax=docker/dockerfile:1
FROM golang:1.23-bookworm AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/server ./cmd/server
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
USER nonroot
ENTRYPOINT ["/server"]The final image contains exactly one file. No shell, no package manager, no libc even — 2MB of binary versus 850MB of toolchain. The security win is bigger than the size win: there's nothing in the image for an attacker to use. No sh means no shell-out, no curl means no easy exfil.
Stages are build targets — use that
docker build --target build -t myapp-dev . # stops at the toolchain stage
docker build -t myapp . # full pipeline, runtime image onlyA test stage between build and runtime — running the unit tests inside the Dockerfile — means CI can't skip them and dev machines can't either. Any stage not on the dependency path to the final stage is skipped entirely, so this costs nothing in production builds.
The patterns that matter
- Compiled languages (Go, Rust, Java): toolchain stage → scratch/distroless runtime. Biggest win in the ecosystem.
- Node/Python: separate
depsstage (install from lockfile) →buildstage (compile/bundle) →runtimestage copies onlynode_modulesproduction deps and the built artifact. Never ship devDependencies. - Cross-compilation with BuildKit:
docker buildx build --platform linux/arm64— the build stage runs under QEMU, the runtime stage doesn't care. One Dockerfile, every architecture.
Field notes
COPY --fromcan pull from any image, not just earlier stages:COPY --from=nginx:1.27 /etc/nginx/nginx.conf /— the correct way to vendor a config.- Multi-stage doesn't shrink images if you copy the world. Audit what the final stage actually needs; every COPY is a decision.
- Alpine is not automatically the right runtime base — musl libc breaks some Python wheels and DNS edge cases. distroless or a slim glibc base is often the safer small image.
- Rebuilding the final image requires only the final stage inputs to change — proper stage ordering keeps rebuilds fast even as the app churns daily.
Was this lesson helpful?