Sub topic 11
Multi-stage builds for smaller images
This chapter assumes you can write a basic Dockerfile, build and run an image, and understand how layers and the build cache work. It builds on the ideas of cache-friendly ordering and build-time versus runtime configuration.
The problem: build tools ship with the app
Compiling a program needs a compiler, headers, a package manager, and often test or lint tooling. Running the program needs none of those. If you build and run in the same image, everything the build needed stays in the final image.
That has three costs:
- Size. The official
golangimage is several hundred megabytes. A static Go binary is a few megabytes. - Attack surface. Every extra package, shell, and compiler is something that can have a vulnerability or be abused after a compromise.
- Leaked intermediate files. Source code, build caches, and credentials used during the build can end up in layers you publish.
Deleting files in a later RUN does not fix this. Layers are additive. A file removed in layer 5 still exists in layer 3, so the image stays just as large.
How a multi-stage build works
A multi-stage build uses more than one FROM in a single Dockerfile. Each FROM starts a new stage with its own filesystem. You can copy files from an earlier stage into a later one. Only the last stage becomes the final image, unless you choose another with --target. Earlier stages are used during the build and are not part of the result.
A complete example in Go
This Dockerfile compiles a static Go binary in a full toolchain image and copies only the binary into a minimal runtime image.
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 .
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]Walk through it stage by stage.
The build stage
FROM golang:1.22 AS build names the stage build. The name is how later instructions refer to it.
The dependency manifests, go.mod and go.sum, are copied first and go mod download runs before the source is copied. This is the same cache-friendly ordering you used for package*.json in the Node.js example. Editing a .go file invalidates the COPY . . layer and everything after it, but the downloaded modules stay cached.
CGO_ENABLED=0 makes Go produce a statically linked binary. A static binary does not depend on shared libraries such as glibc, which is what lets it run in an image with almost nothing in it. The binary is written to /out/app, a path outside the source tree, so it is easy to copy.
The runtime stage
The second FROM discards the Go toolchain and starts from gcr.io/distroless/static-debian12:nonroot. Distroless images contain only what a program needs to run, with no shell and no package manager. The nonroot tag sets the default user to an unprivileged one, which covers the non-root practice from the previous chapter.
COPY --from=build /out/app /app reads from the build stage instead of from the build context. ENTRYPOINT ["/app"] uses exec form, so the binary runs as PID 1 and receives signals such as SIGTERM directly.
Build and compare
docker build -t goapp:multi .
docker images goapp:multiThe image is typically in the single-digit to low double-digit megabytes. A single-stage build on golang:1.22 would be close to a gigabyte. The exact figures depend on your application.
Stage names, indexes, and external images
COPY --from accepts three kinds of source:
| Form | Example | Notes |
|---|---|---|
| Stage name | `COPY --from=build /out/app /app` | Preferred. Survives reordering of stages. |
| Stage index | `COPY --from=0 /out/app /app` | Counts from zero. Breaks if you insert a stage. |
| External image | `COPY --from=nginx:1.27 /etc/nginx/nginx.conf /nginx.conf` | Pulls files from any image without making it a stage. |
Use names. Stage names are case-insensitive but are conventionally lowercase.
Choosing a runtime image
The runtime stage is a choice about what you need at run time. The usual candidates:
| Runtime base | Contains | Use when |
|---|---|---|
| `scratch` | Nothing | A static binary needs no CA certificates, time zone data, or user database. |
| `distroless/static` | CA certificates, time zone data, `/etc/passwd` entries | A static binary that makes TLS calls. |
| `-slim` variants | Minimal distribution with a shell | You need a shell for debugging or the app needs shared libraries. |
| Alpine | musl libc, BusyBox shell | Small size with a shell. Check that your binary works with musl. |
Two common errors come from picking a base that is too small:
exec format erroror "not found" on a binary that exists. A dynamically linked binary was copied into an image that lacks its loader or libraries. Build statically or use a base that has them. This also happens when you build on glibc and run on Alpine's musl.- TLS failures such as "x509: certificate signed by unknown authority".
scratchhas no CA certificates. Either use distroless or copy them from the build stage.
Distroless has no shell, so docker exec -it container sh fails. That is intentional. For debugging, use docker debug where available or build a debug variant of the image.
Multi-stage builds for interpreted languages
Compiled languages are the obvious case, but the pattern also helps with Node.js, Python, and others. The goal is to keep build-only dependencies out of the runtime image.
FROM node:20-slim AS deps
WORKDIR /app
COPY package*.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 ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]The deps stage installs all dependencies, including dev tools such as a TypeScript compiler. The build stage inherits from deps and produces dist. The runtime stage installs only production dependencies and copies in the compiled output. The compiler and dev dependencies never reach the final image.
This example assumes the project has a build script that writes to dist. Adjust the paths to match your project.
Building a single stage with --target
--target stops the build at a named stage. This is useful for running tests or getting a debug image from the same Dockerfile.
docker build --target build -t myapp:build .
docker build -t myapp:1.0 .The first command produces an image from the build stage, which contains the toolchain. The second builds the final stage as usual.
Interaction with the cache
Each stage has its own layers, and each layer is cached by the same rules as before. A few details matter:
- A change in the build stage invalidates the
COPY --from=buildlayer in the runtime stage only if the copied files actually change. - With BuildKit, the default builder in current Docker versions, stages that the final image does not depend on are skipped. With the legacy builder, every stage runs.
- Stages that do not depend on each other can build in parallel under BuildKit. For example, one stage that downloads assets and another that compiles code can run at the same time.
Using ARG across stages
ARG values do not carry across a FROM. An ARG declared before the first FROM is available only to FROM lines unless you redeclare it inside a stage.
ARG GO_VERSION=1.22
FROM golang:${GO_VERSION} AS build
ARG VERSION=dev
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -ldflags "-X main.version=${VERSION}" -o /out/app .
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]GO_VERSION is used in the first FROM. VERSION is declared inside the build stage, so it is available to the RUN that follows. Pass it with docker build --build-arg VERSION=1.4.2 -t goapp:1.4.2 .. The final stage does not see VERSION, and it should not, since build arguments are recorded in image history for the stage that uses them.
Common mistakes
- Copying the wrong path.
COPY --from=buildpaths are absolute paths inside the build stage, or relative to itsWORKDIR. If the build output is not where you think, the build fails with a "not found" error. - Forgetting the runtime stage needs its own setup.
WORKDIR,ENV,USER, andEXPOSEdo not carry over from the build stage. Set them again in the final stage. - Putting secrets in a build stage and assuming they vanish. The final image does not include earlier stages, but the build cache on your machine does, and
--targetcan expose them. Do not write secrets into layers at all. Use BuildKit secret mounts, covered later in this tutorial. - Naming a stage after the final image and expecting it to be tagged. Stage names are internal. Only
-ttags an image. - Using
latestfor the runtime base. Pin a version so rebuilds are reproducible.
Summary of decisions
- Put everything needed only to build in a named build stage.
- Order the build stage for cache reuse: manifests, dependency install, then source.
- Pick the smallest runtime base that still has what the program needs at run time.
- Copy only the artifacts with
COPY --from=<stage>. - Repeat
WORKDIR,ENV,USER, andEXPOSEin the final stage.
Exercise
A teammate writes a Dockerfile with FROM golang:1.22 and a RUN go build step, then adds RUN rm -rf /usr/local/go at the end to shrink the image. The image size barely changes. Why, and how do you fix it?
Show answer
Each instruction creates a layer, and layers are additive. The Go toolchain is stored in an earlier layer, so deleting it in a later layer only hides it from the final filesystem view. The earlier layer still counts toward the image size. The fix is a multi-stage build: compile in a golang stage, then start a new stage from a small base and copy only the binary with COPY --from=build. The toolchain layers then never become part of the final image.
Exercise
You build a static Go binary in a build stage and copy it into a scratch image. The container starts but fails on every HTTPS request with "x509: certificate signed by unknown authority". What is wrong, and what are two ways to fix it?
Show answer
scratch is empty, so it has no CA certificate bundle to verify TLS certificates. One fix is to switch the runtime base to gcr.io/distroless/static-debian12:nonroot, which includes CA certificates. The other is to keep scratch and copy the bundle from the build stage, for example COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/. The second only works if the build stage image actually contains that file, which the Debian-based golang image does.
Exercise
In the Node.js example, which stage would a docker build --target build -t myapp:build . command stop at, and which stages run?
Show answer
It stops after the build stage. The deps stage runs because build inherits from it with FROM deps AS build. The runtime stage does not run, because the target is earlier and nothing the target needs depends on it.