Multi-stage builds

Definition

Multi-stage builds are a feature in Docker that allows the creation of smaller, more efficient container images by using multiple FROM statements in a Dockerfile. Each stage can have its own base image and set of instructions, enabling the separation of build and runtime dependencies. This approach reduces the final image size by copying only the necessary artifacts from the build stages to the final image, enhancing security and performance.

Secure Settings Example

# Build stage
FROM golang:1.18 AS builder
WORKDIR /app
COPY ../../../../PycharmProjects/definitions-for-site/content .
RUN go build -o myapp

# Final stage
FROM alpine:3.15
WORKDIR /app
COPY --from=builder /app/myapp .
ENTRYPOINT ["./myapp"]

Insecure Settings Example

FROM golang:1.18
WORKDIR /app
COPY . .
RUN go build -o myapp
ENTRYPOINT ["./myapp"]

In this insecure example, the final image includes unnecessary build tools and dependencies, increasing the attack surface and image size.