Sobes.tech
Middle+

What is multi-stage build in Docker? Why is it needed?

sobes.tech AI

Answer from AI

Multi-stage build in Docker allows the use of multiple build stages within a single Dockerfile. This helps create compact and optimized images by separating build stages from the final application runtime.

For example, in the first stage, you can build the application with the necessary tools and dependencies, and in the second stage, copy only the compiled artifacts into a minimal image without unnecessary files and build tools.

Advantages:

  • Reduces the size of the final image
  • Enhances security (fewer components in the final container)
  • Cleanliness and ease of managing the Dockerfile

Example:

# Build stage
FROM golang:1.20 AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp

# Final image
FROM alpine:latest
COPY --from=builder /app/myapp /usr/local/bin/myapp
CMD ["myapp"]
What is multi-stage build in Docker? Why is it… - sobes.tech