Sub topic 5
Keeping build tools out of the final image with multi-stage builds
This chapter assumes you can write a Dockerfile, build and run images, and read docker history output. You should also know that every RUN, COPY, and ADD instruction creates an image layer. Earlier chapters covered base images and pinning. Here you will use them to build images that contain only what the application needs at runtime.
Why build tools are a security problem
A typical build needs a compiler, a package manager, header files, and often Git or curl. A running application needs none of these. Each extra tool in the final image causes three problems:
- More known vulnerabilities. Every package in the image appears in a vulnerability scan, whether or not your code uses it.
- More tools for an attacker. If someone gets code execution in the container, a shell,
curl,apt, and a compiler help them download and build further payloads. - Larger images. Bigger images pull slower, and they take longer to scan and replicate.
Cleaning up inside one stage does not fix this. A file removed in a later RUN still exists in the earlier layer, and anyone who pulls the image can extract it. Multi-stage builds solve the problem structurally: the final image is a different image from the one that did the building.
How a multi-stage build works
A Dockerfile can contain several FROM instructions. Each one starts a new stage with its own filesystem. You can name a stage with AS and copy files from it into a later stage with COPY --from=<stage>. Only the last stage becomes the image you tag, unless you choose another with --target. The other stages are used only as sources for COPY --from.
Worked example: a Go service
Go compiles to a single binary, which makes it the clearest case.
# syntax=docker/dockerfile:1
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:nonroot
COPY --from=build /out/app /app
USER nonroot:nonroot
ENTRYPOINT ["/app"]The first stage is named build. It uses the full Go toolchain image, which is large and contains a shell, a package manager, and many libraries. The second stage starts from a distroless static image. That image has no shell, no package manager, and only the files a static binary needs, such as CA certificates and timezone data.
Several details matter:
CGO_ENABLED=0produces a statically linked binary. Without it, the binary may link against glibc, which thestaticimage does not include. The container then fails at start with a confusing "no such file or directory" error, because the dynamic loader is missing.- Copying
go.modandgo.sumfirst lets Docker reuse the cached dependency layer when only source code changes. This speeds up builds and has no security effect. USER nonroot:nonrootmatches the user that the:nonrootimage variant defines. The final image does not run as root.ENTRYPOINTuses the exec form (a JSON array). The distroless image has no/bin/sh, so the shell form would fail.
Build it and compare sizes:
docker build -t myapp:1.0 .
docker build --target build -t myapp:build .
docker images --format '{{.Repository}}:{{.Tag}} {{.Size}}' | grep myappThe myapp:build image will be hundreds of megabytes. myapp:1.0 will usually be a few tens of megabytes at most, depending on your binary. Scan both with docker scout cves or trivy image and the difference in findings is just as large.
Interpreted languages: separate dependencies from build output
Node.js, Python, and Java cannot produce one static binary in the same way, but the pattern still works. The goal is to leave behind everything used only during the build: dev dependencies, compilers, test frameworks, and source files such as TypeScript.
# syntax=docker/dockerfile:1
FROM node:20-slim AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
FROM node:20-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]This Dockerfile has three stages. The deps stage installs only production dependencies. The build stage installs everything, including dev dependencies, and compiles the application. The runtime stage takes production node_modules from deps and compiled output from build. The TypeScript compiler, test runners, and bundlers never reach it.
--chown=node:node sets file ownership during the copy. Without it, copied files belong to root. That is often fine for read-only code, but it matters when the application must write to a copied directory.
Choosing the final stage base
The final stage controls the attack surface. The options trade debugging convenience against exposure:
| Final base | Contains a shell | Typical use | Trade-off |
|---|---|---|---|
| `scratch` | No | Static binaries | Empty image, but you must add CA certificates and users yourself |
| Distroless | No | Static binaries and language runtimes | Small, but harder to debug interactively |
| Slim OS image | Yes | Runtimes that need system libraries | Larger, more packages to scan |
| Full OS image | Yes | Rarely appropriate for production | Largest attack surface |
With scratch there is no /etc/passwd, so USER nonroot fails by name. Use a numeric user such as USER 10001:10001 instead. You also need to copy CA certificates from the build stage if the program makes HTTPS calls:
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/Using stages for tests and for debugging
Named stages also let you run tests without shipping them. Add a test stage that extends build:
FROM build AS test
RUN go test ./...Then run docker build --target test . in CI. The final stage does not depend on test. With BuildKit, which is the default builder in current Docker, stages that the target does not need are skipped. If your pipeline needs tests to gate the release, make the final stage copy something from test, such as a marker file. Otherwise BuildKit can skip the test stage.
For debugging a distroless container, do not rebuild the image with a shell added. Use docker debug, or attach a temporary container that shares the target's process and network namespaces:
docker run --rm -it --pid=container:web --net=container:web busybox shEdge cases and gotchas
- Secrets in early stages are still in the build cache. Files and environment variables from the
buildstage are not in the final image, but they exist in the local builder's cache and in any image you tag from that stage (for example with--target build). Never push a build-stage image. Use--mount=type=secretfor credentials rather thanARGorCOPY, as the secrets chapter covers. ARGandENVdo not cross stages. Values set in one stage are not visible in the next. Redeclare anARGin each stage that needs it, and do not assume a variable from a builder carries into the final image.- Copy specific paths, not whole directories.
COPY --from=build /src /appbrings source code,.gitdata, and test fixtures into the final image. Copy only the artifacts. - Unpinned stage bases defeat reproducibility. Every
FROMshould follow the pinning guidance from the previous chapter. Pin the builder and the final base, ideally by digest. A moving tag in either stage changes what you ship. - Dynamic linking surprises. Python wheels, Node native addons, and Go with cgo can link against system libraries. If the final stage lacks the same library versions, the program fails at runtime. Build in a stage based on the same distribution family as the final one, or build statically.
- Permissions on copied files. Files from the builder keep their mode bits. An executable built with restrictive permissions can fail to run as a non-root user. Check with
docker run --rm --entrypoint ls myapp:1.0 -l /appon images that includels, or inspect the build stage.
Checking your result
After building, confirm that the final image is clean:
- Run
docker history myapp:1.0and look for layers you did not expect, such as a large dependency install. - Run
docker run --rm --entrypoint sh myapp:1.0 -c 'echo hi'. On a distroless or scratch image this should fail, which tells you no shell is available. - Compare
docker scout cvesortrivy imageoutput for the final image and the build stage. The final image should show far fewer packages and findings. - Confirm the user with
docker inspect --format '{{.Config.User}}' myapp:1.0.
Exercise
A teammate's Dockerfile installs gcc in the final image, compiles the app, and then runs apt-get remove gcc && rm -rf /src in a later RUN step. They say the compiler is gone from the image. Is that correct, and how would you fix the Dockerfile?
Show answer
It is not correct. The earlier layers still contain gcc and the source, and anyone can extract them from the image, for example with docker save. Removing files in a later layer only hides them from the merged filesystem view. The fix is to move compilation into a separate build stage, then start a new final stage from a minimal base and use COPY --from=build to bring in only the compiled artifact. Pin both base images and run as a non-root user in the final stage.
Exercise
You switch a Go service to a multi-stage build ending in gcr.io/distroless/static-debian12:nonroot. The container exits at start with "exec /app: no such file or directory", though /app exists. What is the likely cause and the fix?
Show answer
The binary was built with cgo enabled, so it is dynamically linked against glibc. The static distroless image has no dynamic loader or glibc, so the kernel cannot start the binary, and the error refers to the missing loader. Set CGO_ENABLED=0 in the build stage so the binary is statically linked. If cgo is required, use a final base that includes the needed libraries, such as a distroless base image with glibc.