Sobes.tech
Senior

What is multi-stage build in Docker?

sobes.tech AI

Answer from AI

Multi-stage build in Docker is a technique that allows using multiple build stages within a single Dockerfile. It helps create compact and optimized images by separating build and final application runtime stages.

The idea is that in the initial stages, you can use heavy images with compilation and build tools, and in the final stage, copy only the necessary artifacts into a minimal image for running.

Example:

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

# Final stage
FROM alpine:latest
COPY --from=builder /app/myapp /usr/local/bin/myapp
CMD ["myapp"]

This approach reduces the size of the final image and improves security, as the final image does not contain unnecessary tools and source files.