Multi-stage Builds

Build in One Stage, Run in Another

Compilers, dev dependencies and source files 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 image.

Example

A React/Vite frontend: Node builds it, Nginx serves the static files. The final image contains no Node.js and no node_modules:

Dockerfile

# ---- build stage ----
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# ---- runtime stage ----
FROM nginx:1.27-alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80

Go: From 900 MB to 15 MB

FROM golang:1.23 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /app ./cmd/server

FROM gcr.io/distroless/static-debian12
COPY --from=build /app /app
USER nonroot
ENTRYPOINT ["/app"]

Example (size comparison)

docker images myserver

Example output

REPOSITORY   TAG       SIZE
myserver     single    912MB
myserver     multi     14.8MB