Sobes.tech
Middle

In what cases is multi-stage build used?

sobes.tech AI

Answer from AI

Multi-stage build in Docker is used in the following cases:

  1. Reducing the size of the final image: The first (or intermediate) build layer contains tools necessary for compilation, testing, or other build stages (e.g., compiler, build dependencies). The second (final) layer copies only the artifacts needed to run the application (compiled code, executables, runtime libraries). This helps avoid including unnecessary dependencies and build tools in the final image, significantly reducing its size.
  2. Separation of build and run stages: Clear separation of stages makes the build process easier to understand and debug. You can have stages for source code compilation, running tests, linting, and only then create the final image with the ready-to-deploy application.
  3. Security improvement: The final image contains the minimal necessary components, reducing the attack surface. Build tools and source code, which may contain vulnerabilities, do not get into the production image.
  4. Faster build times (in some cases): Intermediate images can be cached, and when only the later stages change, there is no need to rebuild everything from scratch.
  5. Unification of build process: Building the application and creating its Docker image become a single automated process within one Dockerfile, simplifying CI/CD pipelines.

Example for a Go application:

# Build stage
FROM golang:1.20-alpine AS builder
WORKDIR /app
COPY . .
# Build the executable
RUN go build -ldflags="-s -w" -o myapp .

# Final stage
FROM alpine:latest
WORKDIR /app
# Copy only the executable from the previous stage
COPY --from=builder /app/myapp .
# Specify the command to run the application
CMD ["./myapp"]