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
- How do you secure Docker containers and images?
- How does Docker build caching work, and how do you order a Dockerfile to use it well?
- What is a container, and how does it differ from a virtual machine?
- What is the difference between an image and a container, and how do image layers work?
- What are Dockerfile best practices for production images?
- ARG or ENV: what is the difference, and how do you pass secrets into a build safely?
- CMD or ENTRYPOINT: what is the difference, and what are exec and shell forms?
- How do you make Docker images smaller?