Multi-stage Builds

Difficulty: Intermediate

Question

What are multi-stage builds and why should you use them?

Answer

Multi-stage builds allow you to use multiple `FROM` statements in a single Dockerfile. You can compile your code in one stage and 'copy' only the necessary binaries into a tiny final production image.

Code examples

Go App Example

# Stage 1: Build
FROM golang:alpine AS builder
COPY . .
RUN go build -o main .

# Stage 2: Final
FROM alpine
COPY --from=builder /main .
CMD ["./main"]

The final image won't contain the Go compiler or source code, only the 10MB binary, keeping the image small and secure.

Key points

Concepts covered

Optimization, Storage, Build Pipeline