Junior — Middle
How do you apply multi-stage builds to reduce Docker image size?
sobes.tech AI
Answer from AI
Multi-stage build in Docker allows creating images where the first stage involves building the application, and subsequent stages form a minimal image containing only the files necessary to run. This significantly reduces the size of the final image.
Example Dockerfile with multi-stage build for a Go application:
# Build stage
FROM golang:1.20 AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp
# Run stage
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/myapp .
CMD ["./myapp"]
Here, the first stage compiles the binary, and the second creates a lightweight Alpine-based image, copying only the ready-to-run executable.
Thus, heavy build tool images can be used only for compilation, and the final image includes only what is necessary to run.