Dockerfile: Avoid Self-Referencing COPY –from Instructions

COPY --from cannot reference the current stage. Copy artifacts only from previous named stages to avoid invalid multi-stage Docker builds.

Problem

Using COPY with the --from flag to reference the current build stage is not allowed. This mistake leads to build errors and confusion.

Description

In multi-stage builds, COPY --from must target a previously completed stage. Referencing the stage currently being built is logically invalid because artifacts are not finalized yet, so Docker cannot resolve a stable source.

This error often appears during refactoring when stage aliases are renamed or reused. Clear stage ordering and unique aliases prevent ambiguous artifact flow and keep build pipelines deterministic.

Related rules: avoid duplicate FROM aliases, use trailing slash for multi-source COPY, use COPY instead of ADD.

Solution

Reference only prior stages in COPY --from and keep multi-stage dependencies explicit so artifact movement is predictable and reviewable.

Problematic code

FROM ubuntu:20 as builder
USER nobody
RUN apt-get update && apt-get install --no-install-recommends -y build-essential
# Incorrect: referencing the current build stage "builder"
COPY --from=builder /app /app

Verified code

FROM ubuntu:20 as builder
USER nobody
RUN apt-get update && apt-get install --no-install-recommends -y build-essential
FROM ubuntu:20
USER nobody
# Correct: referencing the previous build stage "builder"
COPY --from=builder /app /app

Source of the description

Dockerfile reference: COPY –from