✦ For everyone, free.

Practical knowledge for real and everyday life

Home

5.3.3 Named Build Stages

A focused guide to Named Build Stages, connecting core concepts with practical Docker and container operations.

Named build stages are stages within a multi-stage Dockerfile given an explicit, descriptive name through the AS keyword, making them referenceable by later FROM or COPY --from instructions, and significantly improving a multi-stage Dockerfile's overall readability compared to referencing stages purely by their numeric index.

Naming a Stage

The AS keyword immediately follows a stage's FROM instruction, assigning it a name used to reference it later in the file.

FROM golang:1.22 AS builder
Referencing a Named Stage Elsewhere

Both COPY --from and a subsequent FROM instruction can reference a stage by its assigned name, rather than needing to track which numbered stage corresponds to which purpose.

FROM golang:1.22 AS builder
RUN go build -o /out/app .

FROM scratch
COPY --from=builder /out/app /app
Why Named Stages Are Clearer Than Numeric Indices

Without explicit names, stages are referenced purely by their position (stage 0, stage 1), which becomes increasingly difficult to track correctly as a Dockerfile grows to include more stages.

COPY --from=0 /out/app /app
COPY --from=builder /out/app /app

The second form remains clear and correct even if stages are later reordered or new ones are inserted, while the first would silently break or reference the wrong stage if the numbering shifted.

Choosing Descriptive, Purpose-Reflecting Names

A stage's name should clearly communicate its purpose, helping a reader understand the overall structure of a multi-stage build at a glance.

FROM node:20 AS frontend-build
FROM golang:1.22 AS backend-build
FROM nginx:alpine AS final
Why Named Build Stages Matter

Explicitly naming every stage in a multi-stage Dockerfile is a small effort that significantly improves the file's long-term readability and resilience to future restructuring, making named stages the clearly preferable choice over relying on positional indices.

Content in this section