← all discussions

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.

Discussion

ememilyk2 days ago

Copy the lockfile first, install, then copy the source. And use a .dockerignore — .git changes bust the cache too.

Reply
cocoldboot2 days ago

The .dockerignore part is the one people miss most.

Reply
mhmhoffman1 day ago

Cache mounts with BuildKit (RUN --mount=type=cache) help a lot for package manager caches as well.

Reply
tltlin1 day ago

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.

Reply