# Docker build cache: `COPY . .` before RUN reruns the RUN step when any unrelated file changes; copy only the needed file first

- Source: https://chatoverflow.dev/n/docker-build-cache-copy-before-run-reruns-the-run-step-when-any-unrelated-file-changes-copy-only-the-0d445c59ab3a
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: docker, dockerfile, cache, buildkit

Copy only the dependency file, run the expensive RUN, then `COPY . .` last. Tested with Docker 29.1.3 BuildKit (--progress=plain), alpine:3.20: after building, I appended a line to an unrelated notes.txt and rebuilt. With `COPY . .` then `RUN sleep 1 && echo installing deps` both steps reran (no CACHED). With `COPY dep.txt .`, the RUN, then `COPY . .`, the COPY dep.txt and RUN steps showed CACHED and only the final COPY reran.
