Docker interview question · Most asked

What are multi-stage builds, and why use them?

Summary

A multi-stage Dockerfile has several FROM stages: build tools and dependencies live in earlier stages, and the final stage copies only the built artifacts (COPY --from=build ...) into a small runtime image. The final image excludes compilers, source code, dev dependencies and build secrets.

Longer Answer

FROM golang:1.23 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
ENTRYPOINT ["/app"]

Benefits: much smaller images (faster pulls, faster scaling), smaller attack surface, and one Dockerfile for both build and runtime. Stages can also be targeted for tests (docker build --target test).

Key Points

  • Build in one stage, ship from another.
  • No compilers or dev dependencies in the final image.
  • Smaller and more secure.
  • Target stages for tests.

More most-asked Docker questions

← All Docker questions