Build stage referenced by number

Use a descriptive stage name in COPY --from.

Description

Referring to a build stage by number, such as COPY --from=0, is valid. However, inserting or reordering earlier stages can change the source. Names reduce this dependence on stage order.

Potential impact

A stage-order change can cause the wrong files to be copied or the build to fail.

Remediation

Give the referenced FROM stage a unique name such as AS builder, and use COPY --from=builder.

Examples

The examples reference the same artifact by number and by name. Set GO_BUILD_IMAGE and RUNTIME_IMAGE to supported image references, and ensure that the built artifact’s platform and runtime libraries are compatible with the runtime image.

Before

dockerfile
ARG GO_BUILD_IMAGE
ARG RUNTIME_IMAGE
FROM ${GO_BUILD_IMAGE}
WORKDIR /src
COPY . .
RUN go build -o app .

FROM ${RUNTIME_IMAGE}
COPY --from=0 /src/app /app/app
CMD ["/app/app"]

After

dockerfile
ARG GO_BUILD_IMAGE
ARG RUNTIME_IMAGE
FROM ${GO_BUILD_IMAGE} AS builder
WORKDIR /src
COPY . .
RUN go build -o app .

FROM ${RUNTIME_IMAGE}
COPY --from=builder /src/app /app/app
CMD ["/app/app"]

References