🐳 Docker: Fix a Stale COPY Layer After Editing .dockerignore
Docker’s build cache keys a COPY instruction’s layer off the content hash of exactly what the build context sends it – and that hash is computed only from the files .dockerignore let through the moment the layer was first cached. Editing .dockerignore to newly exclude a file doesn’t retroactively change an already-cached layer’s hash; it only changes what gets sent on a future build. If nothing else that COPY instruction depends on changed, Docker can still report a cache hit and reuse the old layer, silently keeping a file in the image that you just told it to exclude.
🔎 The Problem
# .dockerignore (just edited to exclude secrets/) secrets/ node_modules/ $ docker build -t app . => CACHED [3/6] COPY . . # cache HIT, nothing recomputed # secrets/ was present when that layer was LAST cached; editing # .dockerignore afterward doesn't invalidate that cached hash - # secrets/ may still be inside the already-cached image layer
✅ Fix: Rebuild Without Cache After Any .dockerignore Change
- Rebuild with
docker build --no-cacheafter any.dockerignorechange you expect to affect the image’s contents, rather than assuming a normal build will notice the ignore-file edit on its own. - Verify what actually made it into the image with
docker run --rm <image> ls -la <path>instead of trusting that a successful build means the exclusion took effect. - Treat
.dockerignoreitself as a build dependency in CI, so a change to it automatically forces--no-cache, rather than relying on developers to remember it’s a file the cache doesn’t watch.
🚨 Why This Is Dangerous
- Believing a secrets file is excluded from the image because you added it to
.dockerignore, without confirming the layer actually rebuilt, can ship that file inside an already-cached and now-pushed image.
Docker’s cache watches the files it’s told to send – not the file that tells it which files to send. Rebuild without cache whenever that second file changes.
