Multi-stage Builds
Building software needs much more than running it: compilers, header files, package managers, test tools. A multi-stage build uses several FROM lines in one Dockerfile. Early stages do the heavy building, and the final stage starts from a small runtime image and copies in only the results. Everything else is thrown away.
# syntax=docker/dockerfile:1
# ---- stage 1: build ----
FROM golang:1.24 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/server ./cmd/server
# ---- stage 2: run ----
FROM gcr.io/distroless/static-debian12
COPY --from=build /out/server /server
USER nonroot
ENTRYPOINT ["/server"]AS buildnames a stage.COPY --from=buildcopies files from that stage (you can also copy from any image:COPY --from=nginx:1.27 /etc/nginx/nginx.conf /tmp/).- Only the last stage (or the one you pick with
--target) becomes the image. The Go toolchain never reaches production.
Image size arithmetic
The final image contains the final stage's base plus whatever its own instructions add. Nothing from earlier stages counts, except the files you explicitly copy.
stages = {
"build": {"base": ("golang:1.24", 850), "adds": {"module cache": 180, "source": 3, "/out/server": 14}},
"final": {"base": ("distroless/static", 2), "copies": {"/out/server": 14}},
}
single = stages["build"]["base"][1] + sum(stages["build"]["adds"].values())
final_base = stages["final"]["base"][1]
multi = final_base + sum(stages["final"]["copies"].values())
print(f"single-stage image (build everything in golang:1.24): {single} MB")
print(f"multi-stage image (distroless + binary): {multi} MB")
print(f"saved {single - multi} MB ({100 * (single - multi) / single:.1f}% smaller)")single-stage image (build everything in golang:1.24): 1047 MB
multi-stage image (distroless + binary): 16 MB
saved 1031 MB (98.5% smaller)
Smaller images pull faster, start faster on new nodes, cost less to store and, most importantly, contain fewer packages that could have vulnerabilities.
A Node.js example
Interpreted languages benefit too: install dev dependencies and build in one stage, then install only production dependencies in another.
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM deps AS build
COPY . .
RUN npm run build && npm prune --omit=dev
FROM node:22-alpine AS runtime
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]Targets: one Dockerfile, several images
docker build --target <stage> stops at that stage. A common layout has dev, test and prod stages:
docker build --target test -t shop:test . # run the test suite in CI
docker build --target prod -t shop:1.4 . # the real imageWith BuildKit, the builder works out which stages the target actually depends on and skips the rest. It can also build independent stages in parallel. This model finds the stages needed for a target by following FROM <stage> and COPY --from=<stage> references:
dockerfile_stages = {
"base": {"from": "python:3.12-slim", "copy_from": []},
"deps": {"from": "base", "copy_from": []},
"docs": {"from": "base", "copy_from": []},
"test": {"from": "deps", "copy_from": []},
"assets": {"from": "node:22-alpine", "copy_from": []},
"prod": {"from": "base", "copy_from": ["deps", "assets"]},
}
def needed(target, seen=None):
seen = [] if seen is None else seen
stage = dockerfile_stages[target]
for parent in [stage["from"], *stage["copy_from"]]:
if parent in dockerfile_stages and parent not in seen:
needed(parent, seen)
seen.append(target)
return seen
for target in ["test", "prod", "docs"]:
order = needed(target)
skipped = [s for s in dockerfile_stages if s not in order]
print(f"--target {target:<5} builds {order} skips {skipped}")--target test builds ['base', 'deps', 'test'] skips ['docs', 'assets', 'prod']
--target prod builds ['base', 'deps', 'assets', 'prod'] skips ['docs', 'test']
--target docs builds ['base', 'docs'] skips ['deps', 'test', 'assets', 'prod']
Tip: if you do not pass
--target, the last stage in the file is built. Put your production stage last so a plaindocker build .produces the right image.
Common mistakes
- Copying the wrong path:
COPY --from=build /app/dist ./distmust use the path inside the build stage, which is easy to mistype. When the final image fails with "file not found", run the build stage withdocker build --target build -t dbg . && docker run --rm -it dbg shand look around. - Libraries missing at run time: a binary built against glibc in
golang:1.24won't run on Alpine (musl) orscratch. Build static binaries (CGO_ENABLED=0for Go), or use a runtime base with the same libc. - Forgetting CA certificates and time zone data:
scratchhas none. Distrolessstaticincludes them, which is one reason it is a popular final base.
Test yourself
In a multi-stage build, what ends up in the final image?
- Every layer from every stage
- The final stage's base and its own instructions, including files copied with
COPY --from - Only the first stage
- Only files under /out
What does docker build --target test . do?
- Runs the container's tests
- Builds up to and including the stage named
test(and only the stages it depends on) - Builds the last stage and tags it test
- Pushes to a test registry
Which line copies a file out of an earlier stage named build?
- COPY build:/out/app /app
- COPY --from=build /out/app /app
- FROM build COPY /out/app
- ADD --stage build /out/app