Middle
What are multi-stage builds in Docker and how do they work?
sobes.tech AI
Answer from AI
Multi-stage builds allow the use of multiple temporary images during the Docker build process to obtain a final, optimized image.
How it works:
- Stage separation: The build process is divided into several stages (
FROM), each inheriting from its base image. - Copying artifacts: Files and artifacts created in previous stages are copied to subsequent stages using the command
COPY --from=<stage_name_or_number>. - Final image: The final image is created based on the last stage. Only the files explicitly copied from previous stages are included. Intermediate layers and tools used in earlier stages for compilation or testing are not included in the final image.
Advantages:
- Reduced image size: Only the files necessary to run the application are included in the final image.
- Improved security: Build tools, compilers, and other potentially vulnerable components are not included in the final image.
- Faster build: Intermediate stages can be cached.
- Clean Dockerfile: Different build stages (compilation, testing, packaging) are logically separated.
Example:
# Build stage: Compile the application
FROM golang:1.20 AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -o myapp .
# Run stage: Run the application
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/myapp /app/myapp
CMD ["/app/myapp"]