Named Stage Copying
Named Stage Copying in Docker allows efficient layer reuse during builds by copying files between named stages, optimizing image size and build process
Named stage copying is the practice of using COPY --from=<stage-name> to transfer specific files from a previously defined, explicitly named stage into the current stage, forming the actual mechanism by which artifacts move across the boundaries multi-stage builds establish.
Basic Named Stage Copying
The most direct use copies a single file or directory from a named stage into the current one.
FROM golang:1.22 AS builder
RUN go build -o /out/app .
FROM scratch
COPY --from=builder /out/app /app
Copying From a Stage Defined Earlier in a Longer Chain
In a Dockerfile with several stages, COPY --from can reference any previously defined stage by name, not just the immediately preceding one.
FROM node:20 AS base
RUN npm install -g pnpm
FROM base AS build
COPY . .
RUN pnpm install && pnpm run build
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
The final stage copies directly from build, skipping over base entirely, since only build's output is actually needed in the final image.
Copying From an External Image, Not Just a Local Stage
COPY --from can also reference an entirely separate image, not just a stage defined within the current Dockerfile, which is useful for pulling in a specific tool or artifact from a pre-built image elsewhere.
COPY --from=alpine:3.19 /etc/ssl/certs /etc/ssl/certs
Verifying the Right Files Were Actually Copied
Confirming a named-stage copy operation actually transferred the expected files helps catch a path mistake before it becomes a deployment surprise.
docker run --rm myapp:1.0 ls -la /usr/share/nginx/html
Why Named Stage Copying Matters
COPY --from referencing named stages is the core mechanism that makes multi-stage builds practically useful, providing a precise, explicit, and resilient way to move exactly the needed artifacts across stage boundaries without depending on fragile positional references.