Build stage

2 snippets in Docker

DKDocker

Multi-Stage Builds

DK · Dockerfile
Syntax
FROM <image> AS <stage>
...
FROM <image>
COPY --from=<stage> <src> <dest>
Example
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:20-alpine
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
CMD ["node", "dist/server.js"]

Note The final image only contains the layers from the last FROM stage. Build tools, dev dependencies, and source code from earlier stages are discarded, dramatically reducing image size. A Go API might go from 1.2GB (with SDK) to 15MB (static binary on scratch).

Use Multi-Stage Builds

DK · Best Practices
Syntax
FROM <image> AS build
...
FROM <image>
COPY --from=build ...
Example
FROM golang:1.22 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /app/server .

FROM gcr.io/distroless/static-debian12
COPY --from=build /app/server /app/server
CMD ["/app/server"]

Note The Go SDK (800MB+) stays in the build stage only. The final image is just the static binary on distroless (~2MB). This pattern works for any compiled language and even for frontend builds where you need Node to compile but only serve static files.

Frequently asked questions

How does Docker handle build stage?
Docker covers this with 2 copy-ready snippets on this page. The "Multi-Stage Builds" snippet in Docker uses `FROM <image> AS <stage>`.
Which command does the Docker example use?
The "Multi-Stage Builds" snippet uses `FROM <image> AS <stage>`, from the Dockerfile section of the Docker cheat sheet.
What other Docker snippets are shown for "build stage"?
Besides "Multi-Stage Builds", this page also shows "Use Multi-Stage Builds".
Is there anything to watch out for?
Yes. For "Multi-Stage Builds": The final image only contains the layers from the last FROM stage. Build tools, dev dependencies, and source code from earlier stages are discarded, dramatically reducing image size. A Go API might go from 1.2GB (with SDK) to 15MB (static binary on scratch).