What is a multi-stage build?
A multi-stage build is a way to build a Docker image using several stages (build layers) in a single Dockerfile, so the final image comes out smaller and cleaner.
Why this is needed (junior-level explanation)
Usually building an application needs compilers, dev dependencies, and tools. But the final image doesn't need them and they only take up space. A multi-stage build lets you:
- build the application in one stage,
- and copy only the result into the final image (for example, a binary or compiled code).
What it looks like
Dockerfile
# 1) build stage
FROM golang:1.20 AS builder
WORKDIR /app
COPY . .
RUN go build -o app
# 2) final stage
FROM alpine:latest
COPY --from=builder /app/app /app/app
CMD ["/app/app"]What happens
| Stage | What it does |
|---|---|
builder | Builds the application, includes heavy dependencies |
final | Takes only the finished file and nothing extra |
Summary
- The final image is small
- It contains only what's needed in production
- No dev clutter, no compilers
In one phrase: a multi-stage build is a way to build an application in one image and run it in another, smaller and clean one.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.