Multi-stage Builds

Difficulty: Intermediate

Question

What are multi-stage Docker builds, how do they work, and why should you use them for production images?

Answer

A multi-stage build is a Dockerfile with more than one FROM instruction, where each FROM starts a new stage. You compile or bundle the application in a heavy build stage that has compilers and dev dependencies, then use COPY --from=<stage> to copy only the finished artifacts into a small final stage. The final image ships without build tools or source code, so it is smaller, faster to pull and has a smaller attack surface.

How stages work

  • Each FROM begins a fresh filesystem. Nothing carries over unless you copy it explicitly.
  • Name a stage with FROM golang:1.23 AS builder and reference it later with COPY --from=builder /out/app /app.
  • COPY --from also accepts an external image: COPY --from=nginx:alpine /etc/nginx/nginx.conf /etc/nginx/.
  • Only the last stage (or the one chosen with docker build --target <name>) becomes the output image.
  • With BuildKit, the default builder since Docker Engine 23, stages that the target does not depend on are skipped, and independent stages build in parallel.

Why it matters in production

ConcernSingle stageMulti-stage
Image sizeIncludes compiler, dev deps, cachesOnly runtime artifacts
SecurityShells, package managers, compilers exploitableMinimal or distroless base, fewer CVEs
Pull and start timeSlower autoscaling and rolloutsFaster
Secrets riskBuild-time files can leak into layersBuild stage is discarded

For a statically compiled Go service, the final stage can be scratch or gcr.io/distroless/static, giving an image of a few megabytes. A Node.js or React app commonly drops from over a gigabyte with dev dependencies to a couple of hundred megabytes, or to a tiny nginx image if it is a static frontend.

Patterns you see in real teams

  1. Build then runtime: builder stage runs npm ci and npm run build; runtime stage copies dist/ and production node_modules.
  2. Separate deps stage: a deps stage installs dependencies so the layer is cached independently of source changes.
  3. Test stage: a test stage runs unit tests; CI calls docker build --target test . and the production build never includes test tooling.
  4. Frontend to nginx: compile a React app, copy build/ into nginx:alpine.

Gotchas

  • Copy the right path. In COPY --from=builder /app/main ., the path must match where the builder actually wrote the file; WORKDIR matters.
  • Go binaries built with cgo enabled need libc; for scratch or Alpine use CGO_ENABLED=0 or a matching base.
  • Copying a whole directory like node_modules from the builder brings dev dependencies along; run npm ci --omit=dev in a dedicated stage instead.
  • Use clear stage names like deps, build, runtime instead of relying on numeric indexes such as --from=0, which break when stages are reordered.
Multi-stage build pipeline. Only the compiled artifact crosses from the build stage into the final image.
  1. Stage builder: golang:1.23: Has the Go toolchain and full source tree.
  2. go mod download + go build: Produces one static binary.
  3. COPY --from=builder /out/app: Copies just the binary across stages.
  4. Final stage: distroless/static: No shell, no compiler, a few MB in size.

Code examples

Go service: builder plus distroless runtime

# syntax=docker/dockerfile:1
FROM golang:1.23 AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download            # cached unless deps change
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/api

FROM gcr.io/distroless/static-debian12 AS runtime
COPY --from=builder /out/app /app
USER nonroot:nonroot
ENTRYPOINT ["/app"]

# Build:   docker build -t payments-api .
# Compare: docker images payments-api

The final image contains only the static binary on a distroless base, with no Go toolchain, shell or source code.

React app built with Node, served by nginx

FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:1.27-alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80

# Build only the first stage, e.g. to run tests in CI:
# docker build --target build -t web-build .

Node and node_modules exist only in the build stage; the shipped image is nginx plus static files. --target stops at a named stage.

Key points

  • Each FROM starts a new stage; only the final or --target stage is the output.
  • COPY --from works with named stages and with external images.
  • BuildKit skips unused stages and builds independent stages in parallel.
  • Smaller images mean faster pulls, faster scaling and fewer vulnerabilities.
  • Use CGO_ENABLED=0 for Go when the runtime base is scratch or distroless static.

Common follow-up questions

  • Can you copy from an external image instead of a previous stage?
  • How do you build only an intermediate stage, for example to run tests?
  • What is a distroless image and how do you debug a container without a shell?
  • How would you keep secrets used during the build out of the final image?

Interview tips

  • Quote concrete outcomes: no compiler in production, smaller attack surface, faster pulls during autoscaling.
  • Mention --target and BuildKit's parallel stage builds to show current, practical knowledge.
  • If you have done it, describe the before and after size of an image you optimized; real numbers from your own work beat textbook claims.

Concepts covered

Multi-stage Build, COPY --from, Build Target, Distroless, Image Size

More Docker & Containers questions