Multi-stage builds

Intermediate · 6 min

Build with a full toolchain, ship only the result: named stages, COPY --from, --target for test and debug images, and how BuildKit skips unused stages.

Before thisLayer caching and instruction order

Depot · 6 min

Multi-stage builds

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DepotReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Each FROM starts a new stage with a clean filesystem. Only what you copy across with COPY --from reaches the final image.
  • Name stages with AS so COPY --from=build and --target build keep working when you add or reorder stages.
  • docker build --target <stage> stops at that stage, which gives one Dockerfile a test image, a debug image and a production image.
  • BuildKit builds only the stages the target needs and runs independent stages in parallel. The legacy builder built every stage up to the target.
  • COPY --from can also name any image, such as COPY --from=nginx:1.29 /etc/nginx/nginx.conf, without making it a base.
  • A stage can start FROM an earlier stage to share setup, such as a base stage with system packages used by both dev and prod.

The toolchain is not the product

To compile a Go service you need the Go toolchain, a module cache and the source. To run it you need one static binary. Before multi-stage builds, teams kept two Dockerfiles and a shell script that built in one image, copied the binary out to the host, and built a second image around it. It worked, and it was fragile.

A multi-stage build does both inside one Dockerfile. Each FROM starts a new stage with its own filesystem, and only what you explicitly copy across reaches the final image. It is a workshop and a shipping box: you make the furniture in the workshop, and only the furniture goes in the box, not the saws.

The pattern

# syntax=docker/dockerfile:1
FROM golang:1.25 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/notes ./cmd/notes

FROM build AS test
RUN go test ./...

FROM gcr.io/distroless/static-debian13 AS runtime
COPY --from=build /out/notes /notes
USER nonroot
ENTRYPOINT ["/notes"]

Three stages. build compiles. test starts FROM build, so it inherits the compiled tree and only adds the test run. runtime starts from a base with no shell or package manager and copies in the binary. CGO_ENABLED=0 makes the binary static, which is what lets it run on a base without a C library. Checking sizes through the registry APIs, golang:1.25 for linux/amd64 is 305 MB compressed and distroless/static-debian13 under 1 MB, so the shipped image is roughly the size of the binary.

Name your stages. COPY --from=0 refers to the first stage by position and silently points somewhere else when a stage is added above it.

Only the stages you need

BuildKit treats the Dockerfile as a graph and builds only what the target depends on. The legacy builder processed every stage up to the target. I checked the graph BuildKit produces for the Dockerfile above, using BuildKit v0.35.1’s Dockerfile frontend as a Go library and asking for --target runtime:

[runtime 1/2] FROM gcr.io/distroless/static-debian13:latest@sha256:4c2cd1dee442...
[build 1/6] FROM docker.io/library/golang:1.25@sha256:699337d62055...
[build 2/6] WORKDIR /src
local://context
[build 3/6] COPY go.mod go.sum ./
[build 4/6] RUN go mod download
[build 5/6] COPY . .
[build 6/6] RUN CGO_ENABLED=0 go build -o /out/notes ./cmd/notes
[runtime 2/2] COPY --from=build /out/notes /notes

There is no test step in it. With --target test the graph is the six build steps plus [test 1/1] RUN go test ./..., and no runtime steps. So CI can run docker build --target test . and then build the runtime image, and the second build reuses the cached build stage.

BuildKit also runs independent stages in parallel. A frontend stage running npm run build and a backend stage running go build proceed at the same time when neither copies from the other.

Targets for different jobs

--target turns one Dockerfile into several images:

docker build --target test .                      # run the test suite
docker build --target debug -t notes:debug .      # extra tools for troubleshooting
docker build -t notes:1.4.2 .                     # last stage, the production image

A common shape is a shared base stage with system packages, then dev and prod stages built FROM base. Development gets compilers and file watchers, production gets neither, and both stay in sync on the parts they share.

Copying from images, not just stages

COPY --from accepts any image reference:

COPY --from=nginx:1.29 /etc/nginx/nginx.conf /etc/nginx/nginx.conf
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv

The builder pulls the image and copies only the path you name. It is a clean way to grab a single static tool without a curl | sh in a RUN step. Pin it by tag or digest like any base image.

What to watch for

  • Files copied across keep the ownership they had in the build stage unless you pass --chown. A binary built as root and run as nonroot is fine, but a data directory may need COPY --chown=nonroot:nonroot.
  • ENV and WORKDIR from the build stage do not carry over. The runtime stage inherits only from its own FROM.
  • A dynamically linked binary copied onto a base without its libraries fails at start with a “not found” error that is easy to misread. Match the runtime base to how you linked, which shrinking images covers.

About the video

The embed is the first 5 minutes 41 seconds of Depot’s “Docker Multi-Stage Builds - Fast and Efficient Dockerfiles”, September 2024. The clip covers the problem with large images, implementing a multi-stage build, comparing the results, and caching dependencies. It stops before the last chapter, a pitch for Depot’s hosted builders. It does not show --target or copying from external images, which the lesson adds. English was judged from the channel, the description and the English caption track. anthonywritescode’s video in deeper adds a useful counterpoint on when a single stage is simpler.

What was run: the two build graphs are real output from a Go program calling dockerfile2llb.Dockerfile2LLB in BuildKit v0.35.1, with the golang and distroless references resolved against their registries. The image sizes are sums of compressed layer sizes from the registry manifests, fetched with curl. Nothing was compiled or built. The rest is from the multi-stage builds page and the Dockerfile reference, checked 2026-11-28.

Where this fits

Stages separate building from shipping. Next, passing values into a build and into the container, and keeping the two apart: build arguments and environment variables.

Check yourself

  1. 01A Go service's image is 900 MB because it is built FROM golang. How does a multi-stage build cut that, and what ends up in the final image?

    Compile in a FROM golang AS build stage, then start a second stage from a minimal base and COPY --from=build only the binary. The compiler, module cache and sources stay in the build stage, which is not shipped.

  2. 02Your Dockerfile has build, test and runtime stages, and runtime does not depend on test. Does docker build --target runtime run the tests?

    Not with BuildKit. It works out which stages the target needs and skips the rest, so the test stage never runs. Build --target test in CI to run them.

  3. 03Why is COPY --from=build better than COPY --from=0?

    The number is the stage's position, which changes if someone inserts a stage above it. A name stays correct.

  4. 04How can a stage copy a file out of an image without basing anything on it?

    COPY --from accepts an image reference, for example COPY --from=nginx:1.29 /etc/nginx/nginx.conf /nginx.conf. The builder pulls the image and copies just that path.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark