Docker & Containers

Multi-stage Builds

Produce tiny production images by separating build and runtime.

35 min read intermediate 3 objectives

Status

Not started

What you will learn

  • Use multiple FROM stages
  • Copy only artifacts
  • Slash image size

New to this? Start here

The basics, in plain English

Sometimes building an app needs heavy tools, but running it does not. A multi-stage build uses one big stage to compile, then copies just the finished result into a tiny final image. Smaller images are faster and safer.

Multi-stage build
A Dockerfile with multiple stages, where only the final small one ships.
Build stage
A temporary stage that holds compilers and tools, thrown away at the end.
Artifact
The finished output of a build, like a compiled program, that you keep.
Image size
How big the image is. Smaller means faster downloads and fewer things to attack.
Attack surface
Everything in an image a hacker could exploit. Less stuff means less risk.
01

Build then ship

Compile in a fat builder stage, then COPY only the binary into a minimal runtime stage. This drops image size and attack surface dramatically.

Try it yourself

dockerfile
FROM golang:1.22 AS build
First stage: a full Go toolchain just for compiling.
WORKDIR /src
Work inside /src for the build.
COPY . .
Bring in the source code.
RUN go build -o /app .
Compile a single static binary at /app.
FROM gcr.io/distroless/base
Second stage: a tiny runtime image with no shell or extras.
COPY --from=build /app /app
Copy only the compiled binary from the build stage.
ENTRYPOINT ["/app"]
Run the binary as the container’s main process.
↳ lines explain what each command does — only the commands get copied

Finished this topic?

Mark it done to earn 100 XP and keep your streak alive.