Sub topic 9
Multi-stage builds: leaving build tools behind
This chapter assumes you can read and write a simple Dockerfile, you have run docker build, and you know that each RUN, COPY, and ADD instruction creates a layer. It builds on the previous chapter, where deleting a file in a later layer did not shrink the image.
The problem multi-stage builds solve
A build needs a compiler, headers, package managers, and source code. A running application usually needs only the compiled output and its runtime. If both live in one image, every build tool ships to production.
You could try to clean up inside the Dockerfile. That works only when the download, use, and deletion all happen in one RUN step. Real builds span many steps, and a file written in an earlier layer stays stored in that layer even if a later step deletes it.
A multi-stage build avoids the problem. You describe several stages in one Dockerfile. Each stage starts from its own FROM and has its own layers. The final stage copies only the files it needs from earlier stages. The earlier stages' layers are not part of the final image.
A first multi-stage Dockerfile
This Go example uses two stages.
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app
FROM gcr.io/distroless/static-debian12
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]Read it in three parts.
FROM golang:1.22 AS buildstarts the first stage and names itbuild. This stage contains the Go toolchain, the module cache, and your source tree.- The second
FROMstarts a new stage on a small base image. Nothing from thebuildstage is present here unless you copy it in. COPY --from=build /out/app /appcopies one file from thebuildstage's filesystem into the final stage. It creates one layer in the final image that contains only that binary.
CGO_ENABLED=0 produces a statically linked binary. The static distroless base has no C library, so a dynamically linked binary would fail to start.
The go.mod and go.sum files are copied before the rest of the source. This is the ordering technique from earlier chapters. The go mod download layer stays cached until the dependency files change.
What ends up in the final image
The image you tag is the last stage in the file, unless you choose a different one with --target. Its layers are the base image's layers plus the layers created by that stage's own instructions.
The earlier stages still exist in the build cache. That is useful: a rebuild reuses their layers on a cache hit. But they are not referenced by the final image's manifest, so they are not pushed to a registry and do not count toward the image size.
Naming stages and referring to them
AS name gives a stage a name. Without a name, stages are numbered from zero in file order, so COPY --from=0 refers to the first stage. Names are safer, because inserting a stage later changes the numbers.
--from also accepts an external image. This copies a file straight from a published image without defining a stage for it.
FROM debian:bookworm-slim
COPY --from=busybox:1.36 /bin/busybox /usr/local/bin/busyboxStage names are lowercase by convention, and Docker requires them to be valid reference components, so avoid spaces and uppercase surprises.
Building one stage with --target
docker build --target build -t myapp:build . stops after the named stage and tags that stage's result. This is useful in two ways.
- You can run tests or a debugger in a stage that has the full toolchain, without changing the production image.
- You can keep one Dockerfile for development and production, selecting the stage you want.
A common layout adds a test stage that inherits from the build stage:
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app
FROM build AS test
RUN go test ./...
FROM gcr.io/distroless/static-debian12 AS final
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]FROM build AS test starts a stage from the result of another stage, so it reuses the cached layers. With the classic builder, every stage up to the last is built in order. With BuildKit, which is the default builder in current Docker releases, stages that the target does not depend on are skipped. The final stage above does not depend on test, so a plain docker build . never runs the tests. Run docker build --target test . to execute them. If you want tests to gate the build, make the final stage depend on them, for example by copying a small marker file from the test stage.
Build stages and the cache
Each stage has its own chain of cache entries. The rule from the earlier chapter still applies inside a stage: a miss in one instruction invalidates the later instructions of that stage.
For COPY --from=build, the cache key depends on the content of the files copied from the source stage. If a source edit produces a byte-identical binary, the final stage can still hit the cache. Go builds are often reproducible enough for this to happen. Many other toolchains embed timestamps or paths, so the binary changes on every build and the final COPY always misses. That is cheap here because the final stage is short.
The cost of a miss is concentrated in the build stage, so put your ordering effort there: copy dependency manifests first, install, then copy source.
An interpreted-language example
Multi-stage builds also help for Node.js, where the build output is plain files and the runtime needs only production dependencies.
FROM node:20-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM deps AS build
COPY . .
RUN npm run build
FROM node:20-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
CMD ["node", "dist/server.js"]The runtime stage installs only production dependencies, so TypeScript, bundlers, and test libraries stay out. It copies dist from the build stage. The manifests are copied before npm ci, which keeps that layer cached until the dependency files change.
Common errors and gotchas
- Copying the wrong path.
COPY --from=buildpaths refer to the source stage's filesystem, not your build context. A path that does not exist there fails the build with a "not found" error. Check the source stage'sWORKDIR, because relative paths resolve against the current stage's working directory. - Missing runtime libraries. A binary built on a full image may link against shared libraries that a minimal final image lacks. Symptoms are
not foundorno such file or directorywhen starting a file that clearly exists, which usually means the dynamic loader is missing. Build statically, or choose a final base that includes the libraries. - Lost metadata.
ENV,WORKDIR,USER, andEXPOSEset in an earlier stage do not carry into a stage that starts from a different base. Set them again in the final stage. - Secrets in build stages. Layers of discarded stages are not in the final image, but they stay in the local build cache and may be exported with
--cache-to. Do not write secrets into any layer. Use BuildKit secret mounts instead. - Debugging is harder. Minimal bases such as distroless have no shell. Use a
debugimage variant of the base, or build thebuildstage with--targetto inspect it. - Unused stages cost nothing with BuildKit but run with the classic builder. If you see a stage you did not ask for being built, check which builder you are using.
Verifying the result
Build the Go example and compare it with a single-stage version.
docker build -t myapp:multi .
docker history myapp:multi
docker image ls myappdocker history lists only the layers of the final image. You should see the base image's layers and one layer for the COPY, with none of the go build steps. The size column of docker image ls shows the difference against an image built FROM golang:1.22, which is commonly several hundred megabytes larger.
Choosing where to split stages
Split a Dockerfile into stages when the build needs tools that the runtime does not. Compiled languages, front-end bundles, and anything that downloads a large toolchain are typical cases. Skip it for small scripts that need the same interpreter and packages at build time and run time, because a second stage adds complexity without removing anything.
A useful rule: for each file in the final image, ask whether the running application reads it. If the answer is no, it belongs in an earlier stage.
Exercise
A Dockerfile has a build stage that compiles a binary and a final stage that starts with FROM debian:bookworm-slim. The final stage runs COPY --from=build /src /src and then RUN rm -rf /src/node_modules. The image is still large. Why, and how would you fix it?
Show answer
COPY --from=build /src /src copies the whole source tree, including node_modules, into a layer of the final stage. The later rm -rf only hides those files in a new layer, so the copied data stays stored in the image. Copy only the files the runtime needs, for example COPY --from=build /src/dist /app/dist, so the unwanted files never enter a final-stage layer.
Exercise
You run docker build --target test . with the three-stage Go Dockerfile from this chapter. Which stages run with BuildKit, and does the final stage run?
Show answer
The build stage runs, because test inherits from it, and then the test stage runs. The final stage does not run, because the target is test and nothing in the test stage depends on final.