Sub topic 8
Multi-stage builds for smaller images
This chapter assumes you can write a basic Dockerfile, know how layers and the build cache work, and have run docker build and docker run. It covers how multi-stage builds separate build tools from runtime artifacts, and the errors people commonly hit.
The problem: build tools ship with the app
A compiler, package manager, and source tree are needed to build a program. They are not needed to run it. In a single-stage Dockerfile, everything installed along the way stays in the final image. Layers are only ever added, so deleting a file in a later RUN hides it but does not shrink the image. The earlier layer still holds the bytes.
The result is an image that is large and has a wide attack surface. It carries shells, compilers, and package managers that an attacker could use.
A multi-stage build fixes this. One Dockerfile contains several FROM instructions. Each FROM starts a new stage with its own filesystem. You build in one stage, then copy only the finished artifacts into a clean final stage. Everything else is discarded.
How stages work
Each FROM begins a new stage and a new base image. Stages do not inherit files from earlier ones unless you copy them explicitly. The image you get at the end is the last stage, unless you choose another with --target.
Here is the example from this tutorial's plan:
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"]Reading it from the top:
FROM golang:1.22 AS buildstarts the first stage and names itbuild. This base image contains the full Go toolchain.COPY go.mod go.sum ./followed byRUN go mod downloadcopies only the dependency files first. The download layer stays cached until those files change.COPY . .brings in the source. Changing source code invalidates the cache from this point on, but the dependency download above is reused.CGO_ENABLED=0produces a statically linked binary that needs no C library at runtime. The binary is written to/out/app.- The second
FROMstarts a fresh stage on a distroless base image, which has no shell and no package manager. COPY --from=build /out/app /appcopies one file out of thebuildstage.ENTRYPOINT ["/app"]sets the process that runs when a container starts.
The Go toolchain, module cache, and source never reach the final image.
Building and checking the result
Build the image as usual. Docker runs all stages but tags only the last one.
docker build -t myapp:1.0 .
docker history myapp:1.0docker history lists only the layers of the final stage. You should see a small number of layers, and none from the Go toolchain. Compare docker images output for myapp:1.0 against golang:1.22. The Go image is hundreds of megabytes, while the final image is typically a few megabytes plus the binary.
Targeting a stage
The --target flag stops the build at a named stage:
docker build --target build -t myapp:build .This is useful for debugging a build failure, or for producing a test image that still contains the toolchain. Stages that come after the target are skipped.
A common pattern is a test stage that extends build and runs tests, with the runtime stage kept separate. CI builds --target test, and the release build builds the default.
Copying from other images
COPY --from accepts any image reference, not only a stage name. You can pull a single file out of a published image without making it a stage:
FROM alpine:3.20
COPY --from=nginx:1.27 /etc/nginx/nginx.conf /tmp/nginx.confStages can also build on each other. A stage may use an earlier stage as its base with FROM build AS test, which reuses everything in build.
Interaction with the build cache
Each stage has its own layers and its own cache. The ordering rules from the cache chapter apply inside every stage: put rarely changing instructions first, and copy dependency manifests before source.
Two behaviors are worth knowing:
- A change to a file in the build context only invalidates stages that copy that file. Editing the source does not rebuild a stage that never copies it.
- With BuildKit, the default builder in current Docker, stages that the target does not depend on are not built at all. Independent stages can also run in parallel.
Choosing the final base image
The runtime stage base is a trade-off between size, debuggability, and compatibility.
| Base | Contains | Good for | Cost |
|---|---|---|---|
| `scratch` | Nothing | Static binaries | No shell, no CA certificates, no timezone data |
| Distroless | Minimal runtime files, CA certificates | Static or lightly dynamic apps | No shell for debugging |
| Alpine | Small shell and package manager (musl libc) | Small images with some tooling | musl differs from glibc and can break some binaries |
| Slim Debian | glibc, basic tools | Dynamically linked programs | Larger than the options above |
The binary must match the base. A Go binary built without CGO_ENABLED=0 links against glibc and may fail on scratch or Alpine with an error such as exec /app: no such file or directory. The file exists. What is missing is the dynamic loader it names.
Common errors
COPY failed: file not found. The path after--fromrefers to the stage's filesystem, not your host. Check that the build stage actually wrote the file there, and thatWORKDIRdid not change where you think it is.- Unknown stage name. Stage names are case-insensitive but must match an
ASname defined earlier. A stage cannot copy from one defined later. - Missing runtime files. Programs that make HTTPS calls need CA certificates. On
scratch, copy them from the build stage, for exampleCOPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/. - Copying too much.
COPY --from=build /src /srcbrings the whole source tree back and defeats the purpose. Copy specific artifacts. - Secrets in build stages. Intermediate stages are not in the final image, but they remain in the local build cache. Do not bake secrets into any stage with
ARGorCOPY. Use BuildKit secret mounts instead. - Running as root. A small base does not mean a safe user. Add a
USERinstruction, or use a distrolessnonrootvariant.
When multi-stage builds help less
Interpreted languages such as Python still need their interpreter at runtime, so the saving comes from leaving behind compilers, headers, and build dependencies. A typical pattern builds wheels in one stage and installs them in a slim runtime stage. For Node.js, install dev dependencies and run the build in one stage, then copy dist and production dependencies into the final one. The gain is real but smaller than for compiled static binaries.
Exercise
A Dockerfile has a stage FROM golang:1.22 AS build that compiles /out/app, then a final stage FROM scratch with COPY --from=build /out/app /app. The image builds, but docker run prints exec /app: no such file or directory. What is the likely cause, and how do you fix it?
Show answer
The binary was probably dynamically linked against glibc, and scratch has no dynamic loader or C library. The file exists, but the loader it references does not. Rebuild with CGO_ENABLED=0 so the Go binary is statically linked, or use a final base that provides the required libraries, such as a glibc-based image.
Exercise
You edit a README that your Dockerfile never copies into any stage. Does the next docker build rebuild the build stage? What if you edit a .go file instead?
Show answer
Editing the README does not rebuild anything, because no instruction copies it and the layer cache keys stay the same. Editing a .go file invalidates the cache at COPY . . and every instruction after it in the build stage, including the compile step. The go mod download layer remains cached because go.mod and go.sum did not change. The final stage copies a new binary, so its COPY --from=build layer also rebuilds.