Sobes.tech
Middle

In what cases is multi-stage assembly used?

sobes.tech AI

Answer from AI

Multi-stage builds are used to optimize the size and security of the final Docker image, as well as to separate build stages.

Main use cases:

  • Reducing image size: By using different base images for dependencies and final application creation, you can exclude build tools, source code, and other unnecessary files from the final image.
  • Enhancing security: A smaller image size means a smaller attack surface. Additionally, confidential information (such as SSH keys used for cloning private repositories during build) does not end up in the final image.
  • Separating build stages: Different stages can compile code, build frontend assets, run tests, and only then copy necessary artifacts into the final image. This makes the Dockerfile more readable and maintainable.
  • Using different base images for different tasks: For example, using an image with a Go compiler installed for building an executable, and then copying this file into a minimal Alpine image for running.

Example of a Dockerfile with multi-stage build:

# First stage: build the Go application
FROM golang:1.20 as builder

WORKDIR /app
COPY go.mod ./
COPY go.sum ./
RUN go mod download
COPY *.go ./
RUN go build -o /app/myapp

# Second stage: create a minimal image
FROM alpine:latest

WORKDIR /app
COPY --from=builder /app/myapp .

EXPOSE 8080
CMD ["./myapp"]