What is multi-stage Docker build?
· Category: Docker
Short answer
Multi-stage builds allow you to use multiple FROM statements in a Dockerfile. Each stage can copy artifacts from previous stages, letting you compile code in a full build environment and ship only the runtime artifacts in a minimal final image.
How it works
The Dockerfile defines multiple stages, each starting with FROM. The COPY --from=stage instruction copies files between stages. Only the final stage is included in the output image, leaving behind build tools and intermediate files.
Example
# Build stage
FROM golang:1.21 AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o myapp
# Runtime stage
FROM gcr.io/distroless/static-debian11
WORKDIR /app
COPY --from=builder /app/myapp .
CMD ["./myapp"]
Build:
docker build -t myapp .
Why it matters
Multi-stage builds reduce image size by excluding compilers, headers, and build caches. Smaller images deploy faster, reduce attack surfaces, and lower storage costs. This pattern is essential for production-grade containerization.
Common issues
- Copying the wrong artifacts between stages results in missing runtime files.
- Build caches are not shared between stages unless explicitly configured.
- Distroless images lack a shell, making debugging harder.