Junior — Middle
Explain the concept of multi-stage builds in Docker and its advantages.
sobes.tech AI
Answer from AI
Multi-stage build in Docker allows using multiple build stages within a single Dockerfile. This means you can first build the application in one container with the necessary tools and dependencies, and then copy only the required artifacts into the final image, which will be minimal and lightweight.
Advantages:
- Reduces the size of the final image, as build tools and temporary files are not included.
- Increases security, as the final image does not contain unnecessary components.
- Easier maintenance and readability of the Dockerfile, since all stages are described in one place.
Example for Go:
# Build stage
FROM golang:1.20 AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp
# Final image
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/myapp .
CMD ["./myapp"]