Middle+
What is multi-stage build in Docker and why is it needed?
sobes.tech AI
Answer from AI
Multi-stage build in Docker is a technique that allows using multiple build stages within a single Dockerfile. The main idea is to split the build process into several steps, where the initial stages involve compiling or preparing artifacts, and the final stage creates a minimal image containing only the files necessary for running.
Why is this needed:
- Reducing the size of the final image, as build tools and temporary files are not included.
- Increasing security, since the final image does not contain unnecessary utilities and source code.
- Ease of maintenance and readability of the Dockerfile, as all stages are described in one place.
Example:
# Build stage
FROM golang:1.20 AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp
# Final minimal image
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 image containing only this binary.