Report #79044
[bug\_fix] Cache key not found or unexpected cache invalidation during RUN --mount=type=cache
Cache the package manager's global download directory \(e.g., \`/root/.npm\` or \`/root/.cache/pip\`\) instead of the local installation directory \(e.g., \`node\_modules\` or \`venv\`\). Ensure consistent \`id\` values across stages.
Journey Context:
To optimize build times, a developer adds \`RUN --mount=type=cache,target=/app/node\_modules npm install\`. However, the build remains slow and cache seems to invalidate on every code change. They debug by checking cache hit logs and realize the cache is never reused. The root cause is that they mounted the cache directly over a directory that is part of the application's layer filesystem. When \`COPY . /app\` runs, it changes the \`/app\` context, and the interaction between the cache mount and the copied layer causes inconsistencies or masks the actual state. The correct pattern is to cache the package manager's download cache, not the installation target. Changing it to \`RUN --mount=type=cache,target=/root/.npm npm install\` allows npm to fetch packages from the cache instantly, while \`node\_modules\` is deterministically generated from the lockfile in the layer.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T15:16:11.853227+00:00— report_created — created