Docker Build Cache: Fix Slow Builds and Stale Results
Diagnose Docker build cache misses and stale results with BuildKit logs, Dockerfile ordering, cache mounts, .dockerignore, and targeted rebuild commands.
Find the first unexpected build step before changing the cache. For slow builds, check its inputs and whether the selected builder has reusable cache. For stale results, check whether the Dockerfile actually declares the changed input. Use --no-cache to rerun build instructions and --pull to check for newer base images; these flags solve different problems.
Decide whether the problem is a miss, a stale hit, or deployment
A developer changes one source file and waits while the dependency installation runs again. Another rebuilds a container image but still sees yesterday’s generated configuration. Both describe the problem as “Docker cache is broken.” They need different investigations: the first build may invalidate too much; the second may omit an input that should have changed its result.
Start by writing the expected behavior for the next build. For example: “Changing src/handler.js should rerun the application build, while preserving the dependency-install result.” That statement gives you a boundary to inspect. “Make Docker faster” does not tell you which skipped or repeated step would be correct.
Also separate an image build from running the image. If a new image contains the expected file but the application serves old content, investigate which image the container actually runs, runtime mounts, and application-level caching. Rebuilding an image does not by itself establish that the deployment uses it. In a Kubernetes environment, the companion probe guide below can help distinguish container health from traffic eligibility.
Capture a comparable build before changing anything
Use Buildx with plain progress output so you can identify individual steps and their cache status. The commands below assume Docker with Buildx is installed and a builder is available. Run them from the intended project root. The dot is the build context, not a decorative suffix. --load puts a single-platform build result into the local image store for inspection.
Build twice without editing the project between runs. Record the selected builder, the command, the Git revision, and the first expensive step that reruns. Do not compare a local warm build with a fresh CI builder and attribute the entire difference to the Dockerfile. Keep target stage, build arguments, platform, and input files the same during this baseline.
Log step labels alongside duration. A cache hit followed by a slow image export is different from a long package installation. Likewise, time spent transferring a context calls for a different fix from time spent executing a compiler. Preserve enough log context to locate the delay, while removing credentials or private data before sharing the output.
docker buildx ls
docker buildx build --progress=plain --load -t cache-demo:baseline .
# Repeat without changing project files or build options.
docker buildx build --progress=plain --load -t cache-demo:baseline .Source: Docker Buildx build command: progress, stages, and output ↗
Follow the first unexpected cache miss to its input
Docker checks whether an instruction and its relevant inputs match a reusable result. For a COPY instruction, changed source content or relevant metadata can invalidate the step; modification time alone is excluded from the cache checksum. An unchanged RUN command does not automatically become stale merely because a remote package repository has changed.
In a dependent sequence, a changed earlier result causes later work to rebuild. Start at the earliest unexpected miss rather than the final slow step. If COPY . . changes before dependency installation, the reinstall may be a consequence of copying an unrelated edited file, not evidence that the package manager ignored its lockfile.
For each unexpected miss, compare the exact instruction and inputs between the two builds. Look for generated files, changing build arguments, a different base image, or a different context. Change one suspected input and repeat. Keep a short explanation with the result: “dependency installation reran because package-lock.json changed” is actionable; “cache sometimes works” is not.
For a stale hit, reverse the question: what changed outside the declared inputs? A remote resource downloaded by an unchanged command needs an explicit freshness strategy. Secret contents also do not invalidate the build cache when changed. Where a secret-dependent result needs refreshing, use a separate nonsecret revision input or a targeted rebuild; never use the secret value itself as a build argument.
Put dependency inputs before frequently edited source
The following is a build-stage example for an npm project that already has package.json, package-lock.json, and a working build script. It is not a complete production runtime image. The Node tag is an illustrative base choice; retain a compatible base and update policy for your application. The Dockerfile frontend declaration enables the BuildKit syntax used by the cache mount.
The dependency stage copies the package manifests first. The application source enters only in the build stage, so a source-only edit does not directly change the earlier manifest-copy input. The named stages also make a targeted dependency rebuild possible. The package-download cache mount is separate from reusing the result of the installation instruction.
Check your project’s install lifecycle before adopting this split. If installation generates code from a schema, compiles local packages, or reads workspace manifests, those files are dependency-install inputs too. Copy the required inputs before installation. A neat-looking Dockerfile that omits them may be incorrect, even if it produces more cache hits.
Run the application’s normal verification against the result. Moving a COPY boundary is an optimization only when it preserves the intended build. For a monorepo, map the package manager’s actual input graph before reducing the copied files. Do not assume the two manifest files in this small example describe every repository.
# syntax=docker/dockerfile:1
FROM node:24-bookworm-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
FROM deps AS build
COPY . .
RUN npm run buildCheck the context and .dockerignore together
The build context determines which local files the build can access. With docker buildx build -f docker/Dockerfile ., the Dockerfile is selected from docker/, but the context remains the current directory. COPY source paths are interpreted against that context. Choosing another Dockerfile location does not automatically make its containing directory the context.
Put .dockerignore at the context root. A Dockerfile-specific ignore file can also exist and takes precedence over the root ignore file for that Dockerfile. Investigate both when local and CI behavior differ. The example below excludes common host artifacts for the npm build shown above; adapt it rather than copying it into an unrelated project.
Exclude files because they are irrelevant to the intended build, not because excluding them hides a failure. In particular, do not exclude the lockfile or generated inputs that installation genuinely needs. Review the exclusion list when introducing workspaces, local packages, or build-time assets. A smaller context is useful, but the context must still contain a complete set of inputs.
node_modules
.git
dist
coverage
npm-debug.log*
.env
.env.*Choose a targeted rebuild or a full refresh deliberately
A clean build and a base-image refresh are separate operations. --no-cache tells the build to rerun instructions without normal build-cache reuse. --pull asks the builder to check for newer referenced images. Combining them is useful for investigating freshness, but it does not override a dependency lockfile or guarantee that remote resources have changed.
Use the first command below when the question is specifically whether rerunning the deps stage changes the result. Use the second when you deliberately want a broader clean-build comparison with refreshed base-image resolution. Both use the named build stage from the earlier example. Keep the same source revision while comparing their outputs.
Inspect what changed, not just whether the second build passed. If a clean build fixes the output, identify which dependency or remote input was absent from the reusable build contract. Leaving every build permanently uncached can conceal that omission. If the output remains old, move on to file selection, generation logic, and the running deployment instead of repeating cache-clearing commands.
# Rerun the named dependency stage, keeping a focused comparison.
docker buildx build --target build --no-cache-filter deps \
--progress=plain --load -t cache-demo:deps-refresh .
# Deliberately rerun the build and check for fresher base images.
docker buildx build --target build --pull --no-cache \
--progress=plain --load -t cache-demo:clean .A package cache helps a rerun; it does not eliminate the rerun
Two successful optimizations can look different in the log. Reusing a cached installation result skips executing that instruction. A cache mount instead provides reusable package-download data when the instruction executes again. A lockfile change can therefore cause installation to rerun while still benefiting from previously downloaded packages.
Do not treat a long-running instruction as proof that the cache mount is absent. The package manager may still have meaningful installation or compilation work. Measure the part you are trying to improve. Cache mounts are performance aids, so the build should also remain correct with an empty cache; required build artifacts must not exist only in a cache directory.
This distinction also explains why a normal layer-cache export should not be assumed to preserve every package-manager cache mount across disposable CI runners. Decide separately how your CI retains those caches. Record which mechanism is expected to skip work and which merely makes repeated work cheaper, then validate each on a fresh runner.
When local builds are fast but CI keeps rebuilding
BuildKit keeps an internal cache, but a new CI builder may not have the results your laptop has accumulated. External cache storage can carry reusable results between runs. The --cache-to option exports cache; --cache-from imports it. Confirm both operations in logs, along with the selected backend and builder support.
A successful application-image push is not sufficient evidence that a separate cache export succeeded. Check the exact cache destination, authentication, import warnings, and whether different jobs overwrite the same reference. If you maintain branch-specific caches, choose distinct export locations and an explicit fallback policy rather than letting every branch compete for one location.
For an initial investigation, avoid adding multiple backends at once. Choose one backend supported by your builder, complete a build that exports cache, and run a comparable second job that imports it. Then make a controlled source-only change. Compare the earliest cache decision against your stated expectation. This gives you evidence of actual reuse rather than a configuration file that merely contains cache flags.
A small experiment that separates correctness from speed
The sequence below is a proposed diagnostic exercise, not a published benchmark or a claim that these commands were run against your application. Use a disposable branch or copy of the project. Keep the builder and build options fixed, and record actual observations rather than copying an expected log into an incident report.
First, build twice without changes. Next, edit one application source file and predict which step should first rebuild. Then make an intentional dependency change using the project’s package-management workflow and repeat. Finally, compare a targeted dependency refresh with a clean build when investigating freshness. Inspect the resulting artifact after each meaningful change.
The outcome should explain both sides: why unchanged inputs reused a result, and why a changed required input produced a new result. Do not optimize for the largest number of cached steps. Optimize for a correct artifact with avoidable work removed. Once that behavior is understood locally, reproduce it on a clean CI runner and document the cache import and export boundary.
- Record command, builder, source revision, target, and platform.
- Locate the first unexpected cache decision, then identify its declared inputs.
- Change one input and compare the new artifact as well as the build log.
- Retain the smallest Dockerfile or CI change that preserves correctness.
Your next steps
- Trace the earliest unexpected cache decision before changing the final slow step.
- Keep source, dependency inputs, layer reuse, and package caches separate in your diagnosis.
- Use targeted or clean rebuilds to test a hypothesis, then fix the missing input or cache boundary.
Sources & official resources
Linked resources checked on 2026-10-22. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →