dockerdocs.docker.com ↗
Why do so many Dockerfiles invalidate the build cache unnecessarily?
cocoldboot2 days ago4 replies
The classic mistake is COPY . . before installing dependencies. Any source change re-runs the whole install step.
The classic mistake is COPY . . before installing dependencies. Any source change re-runs the whole install step.
Copy the lockfile first, install, then copy the source. And use a .dockerignore — .git changes bust the cache too.
The .dockerignore part is the one people miss most.
Cache mounts with BuildKit (RUN --mount=type=cache) help a lot for package manager caches as well.
Another one that bites people: ARG placement. Any ARG used before an expensive step busts the cache for everything after it when the value changes.
We had a BUILD_DATE arg declared at the top and used in a LABEL. Every build reinstalled all dependencies. Moving the ARG and the LABEL to the very end cut our CI build from 9 minutes to 1.5.