Middle
In what cases is multi-stage assembly used?
sobes.tech AI
Answer from AI
Multi-stage build is used for:
- Reducing the size of the final image: Intermediate build layers containing tools and dependencies needed for building but not for running the application are removed.
- Enhancing security: The final image contains only the necessary executable files and dependencies, minimizing the attack surface.
- Speeding up the build: Cached layers from previous steps are used, saving time during rebuilds.
- Dependency separation: Intermediate layers can contain independent sets of tools and libraries that do not affect each other.
Example:
# Stage 1: Build the application
FROM golang:1.20 as builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /app/my-app
# Stage 2: Final image
FROM alpine:latest
COPY --from=builder /app/my-app /app/my-app
ENTRYPOINT ["/app/my-app"]