Multi-stage builds
Build with all the tools, ship only what you need to run.
Compilers and build tools are needed to build an app but not to run it. A multi-stage build uses one stage to build and copies only the result into a small final stage.
# Stage 1: build
FROM golang:1.23 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app
# Stage 2: run
FROM gcr.io/distroless/static-debian12
COPY --from=build /out/app /app
USER nonroot
ENTRYPOINT ["/app"]- Only the last stage becomes the image you ship.
COPY --from=buildtakes files from an earlier stage.- The final image has no compiler, no source code and a far smaller attack surface.
FROM node:22 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:1.27-alpine
COPY --from=build /app/dist /usr/share/nginx/htmlChoosing a base
| Base | Size | Note |
|---|---|---|
ubuntu or debian | Large | Full tools, easy to debug |
-slim variants | Medium | A good default |
alpine | Small | Uses musl instead of glibc. A few programs behave differently |
distroless | Very small | No shell or package manager, which is great for security and harder to debug |
NoteBuild a specific stage with docker build --target build ., which is handy to debug a build or run tests in CI.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.