Description
When COPY --from references the alias of its current stage in a multi-stage Dockerfile, the stage depends on its own output. This circular dependency causes the image build to fail.
Potential impact
- Failed image builds can delay deployment or recovery.
- Unclear stage responsibilities and artifact flow can make maintenance harder.
Remediation
- Use ordinary COPY for files from the build context. For artifacts from another stage, specify that stage’s name in COPY --from.
- Check for cycles between stages and verify artifact paths and runtime compatibility in the final image. Also verify that any external image or named-context references are intentional.
Examples
The existing examples compare Go build stages. They require actual source and module files, and the final binary must be compatible with Alpine libraries and the target architecture.
Before
dockerfile
FROM golang:1.22 AS builder
WORKDIR /src
COPY --from=builder /src/app /app
RUN go build -o /src/app .
After
dockerfile
FROM golang:1.22 AS builder
WORKDIR /src
COPY . .
RUN go build -o /src/app .
FROM alpine:3.20
WORKDIR /app
COPY --from=builder /src/app /app/app
CMD ["/app/app"]
Explanation:
- Before: The builder stage references itself through COPY --from=builder, so the build cannot complete.
- After: The separate runtime stage copies the artifact produced by builder. Source completeness and runtime compatibility still need verification.