Skip to content

Lesson 7 of 9 · 25m

Multi-Stage Builds and Minimal Runtime Images

Separate build-time toolchains from runtime artifacts, preserve reproducibility, and avoid shipping compilers, credentials, and debug debris to production.

The best container image is boring: it contains exactly what the process needs, starts predictably, and gives vulnerability scanners very little to shout about. Multi-stage builds are the primary Docker mechanism for that discipline. They let you compile in a capable environment and copy only artifacts into a small runtime image, instead of shipping the entire toolchain because cleanup was inconvenient.

Build environment is not runtime environment

A typical Go example:

FROM golang:1.23-bookworm AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/server ./cmd/server

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
USER 65532:65532
ENTRYPOINT ["/server"]

The final image has no shell, compiler, package manager, module cache, or source tree. That reduces attack surface and noise. It also forces better operational discipline: debugging must come from logs, metrics, and deliberate debug images rather than randomly shelling into production.

Multi-stage does not automatically mean minimal

This pattern is still sloppy:

FROM node:22 AS build
WORKDIR /app
COPY . .
RUN npm ci && npm run build

FROM node:22
WORKDIR /app
COPY --from=build /app .
CMD ["node", "server.js"]

It copies the whole application directory, including dependencies and perhaps tests, build artifacts, or sourcemaps. Copy the precise runtime artifact and production dependency set:

FROM node:22-bookworm-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]

Cache mounts improve speed without shipping secrets

BuildKit cache mounts keep dependency caches out of final layers:

# syntax=docker/dockerfile:1.7
FROM python:3.12-slim AS build
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip     pip install --prefix=/install -r requirements.txt

Secret mounts are for build-time credentials:

DOCKER_BUILDKIT=1 docker build   --secret id=npmrc,src="$HOME/.npmrc"   -t registry.internal/app:2.4.1 .
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci

Never use build args for private credentials if the value would be sensitive in image metadata or history.

Choose the smallest base that honestly fits

scratch, distroless, Alpine, slim Debian, and full distributions are tradeoffs, not a moral hierarchy. Static binaries fit scratch and distroless well. Dynamic language runtimes often fit slim bases better. Alpine's musl can change DNS, locale, memory allocation, and native dependency behavior. Choose based on compatibility and operational evidence, not image-size leaderboard pride.

Verify the artifact, not just the build success

docker image inspect registry.internal/app:2.4.1   --format '{{.User}} {{json .Config.Entrypoint}}'
docker run --rm registry.internal/app:2.4.1 --version
docker history registry.internal/app:2.4.1 --no-trunc

Check that the runtime user is non-root, the entrypoint is correct, labels identify source revision, and final layers do not contain source credentials or toolchain caches.

Field notes

  • Multi-stage copy paths are literal; a missed trailing directory can silently alter layout.
  • .dockerignore still matters because oversized contexts slow builds and leak irrelevant files into build stages.
  • A shellless final image complicates emergency debugging; keep a controlled debug variant rather than weakening every production image.
  • Build provenance labels such as org.opencontainers.image.revision make incident response much easier.
  • Minimal images reduce surface, but they do not patch vulnerable application dependencies. Scan content, not just the base name.

Was this lesson helpful?

Sign in to rate