appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Multi-stage builds

Lesson 2 of 411 minIntermediate

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=build takes files from an earlier stage.
  • The final image has no compiler, no source code and a far smaller attack surface.
A web front end: build with Node, serve with nginx
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/html

Choosing a base

BaseSizeNote
ubuntu or debianLargeFull tools, easy to debug
-slim variantsMediumA good default
alpineSmallUses musl instead of glibc. A few programs behave differently
distrolessVery smallNo 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.

1. What ends up in the final image of a multi-stage build?
2. Which instruction copies from a previous stage?
3. A drawback of distroless images?

Key terms