Imagine a pull request that changes one line of CSS in a React app. CI still spends most of its time on npm ci for both the frontend and the NestJS API, then rebuilds both images layer by layer. On a laptop, the same build would be almost instant, because Docker reuses its local cache. In CI, every job starts on a fresh runner with an empty cache.
The fix is to give BuildKit a cache that outlives the runner, and to write Dockerfiles that let it work.
Faster CI builds that stay correct come down to a few decisions:
- Order the Dockerfile so dependency installation only reruns when the lockfile changes.
- Export the build cache to the GitHub Actions cache or a registry, with a separate scope per image.
- Build on the default branch, so feature branches have a cache to start from.
- Keep the cache from hiding an outdated base image.
- Write the shared cache only from trusted workflows.
- Measure cache hits instead of guessing.
Why CI rebuilds everything
Docker builds an image as a chain of layers, one for each instruction. Docker's build cache documentation puts the key rule plainly: if a layer changes, all the layers after it are affected too. Change a file that's copied early, and every step after that copy runs again.
Locally, the cache lives on your machine. A GitHub-hosted runner is a new virtual machine for each job, so the local cache is always empty. Unless you export the cache somewhere and import it on the next run, BuildKit has nothing to reuse.
Two things make that work:
- A Dockerfile order that keeps expensive steps stable.
- A cache backend that stores layers between runs.
Order the Dockerfile so the cache can work
Docker's cache optimization guide recommends putting the steps that change most often near the end, and copying package manager files before the rest of the source. For a Node.js app, that means:
- Copy
package.jsonandpackage-lock.jsonfirst. - Run
npm ci. - Copy the application source.
- Run the build.
With that order, a source change invalidates only the steps after the source copy. The npm ci layer is reused as long as the lockfile and package file haven't changed.
Add a .dockerignore that excludes node_modules, build output, .git, local env files, and test reports. Without it, an unrelated file change can still invalidate the copy step, and you might send secrets or huge folders into the build.
Use multi-stage builds so the final image doesn't carry build tools:
- NestJS API: a build stage installs all dependencies and compiles TypeScript. The runtime stage installs only production dependencies, with
npm ci --omit=devas documented in the npm ci reference, and copies in the compiled output. - React app: a build stage produces static files, and the runtime stage is a small web server image that serves them. No Node.js or
node_modulesship to production.
Docker's documentation notes that BuildKit only builds the stages the target depends on. A --target for tests can share the cached dependency stage with the production build.
Two caches for npm: the layer and the mount
npm benefits from two different caches, and it helps to know which one does the work.
The layer cache. When the lockfile hasn't changed, the whole npm ci step is a cache hit. Nothing is downloaded or installed. With a good Dockerfile order, this is the common case.
The cache mount. When the lockfile does change, the npm ci layer must run again. A cache mount on npm's cache directory, /root/.npm for the root user, lets npm reuse previously downloaded packages instead of fetching everything again. You add it to the RUN instruction with the --mount=type=cache option.
There's a catch in CI. Docker's GitHub Actions cache guide says BuildKit doesn't preserve cache mounts in the GitHub Actions cache by default. The guide points to a community action, buildkit-cache-dance, that moves the mount contents in and out of the cache. That adds moving parts. Many teams get most of the benefit from the layer cache alone, and only add the mount workaround if lockfile changes are frequent.
A common misconception: the npm caching option in the setup-node action caches npm's directory on the runner, which helps steps that run npm directly on the runner. It doesn't reach inside a docker build, which has its own filesystem.
Export the cache: GitHub Actions cache or your registry
BuildKit can export and import its cache through several cache backends. As of November 2026, Docker lists:
- inline: the cache is embedded in the image itself.
- registry: a separate cache image in a registry.
- local: a directory.
- gha: the GitHub Actions cache, marked beta.
- s3 and azblob: Amazon S3 and Azure Blob Storage, both marked experimental.
Two settings matter most:
- Mode. The default
mode=mincaches only the layers that end up in the final image.mode=maxalso caches intermediate stages. With multi-stage builds, the dependency and build stages are the valuable ones, somaxusually pays off. It also stores more. Docker's GitHub Actions cache guide notes that the inline exporter only supportsmin. - Builder. Use the setup-buildx action, which creates a builder that supports cache export. Some backends don't work with the default docker driver.
The GitHub Actions cache backend. You pass type=gha to the cache-from and cache-to inputs of the build-push action, as described on Docker's gha backend page. Per Docker's GitHub Actions cache guide, only version 2 of GitHub's cache service API has been supported since April 15, 2025. That requires Buildx 0.21.0 or later and BuildKit 0.20.0 or later. Older pinned action versions or self-hosted setups can break here. As of November 2026, the build-push action is on v7 and setup-buildx on v4.
A registry cache. With type=registry, the cache is pushed as a separate image, for example a buildcache tag in the same Azure Container Registry you deploy from, per Docker's registry backend page. It isn't limited by GitHub's cache size, and other systems can share it. Docker's documentation doesn't list registry-specific compatibility notes, so test cache export and import against your registry before relying on it. Cache images also count toward registry storage, so plan to clean them up.
If your workflow already signs in to Azure with OIDC, the same login can push the registry cache. The earlier post on OIDC federated credentials covers that setup.
Two images, one cache budget
A repository with an API and a web image needs separate cache entries per image. The gha backend's default scope is buildkit. Docker warns that if you build multiple images, each build overwrites the previous one's cache, leaving only the last. Give each image its own scope, such as scope=api and scope=web, on both cache-from and cache-to.
The images still share one budget. Per GitHub's dependency caching reference:
- Each repository gets 10 GB of cache by default.
- Entries not accessed in over 7 days are removed.
- Once the limit is reached, older entries are evicted.
mode=max on two images can fill that quickly. Since a November 2025 change, eligible accounts can raise the limit with pay-as-you-go billing. A registry cache is the other way out.
npm workspaces add a subtle coupling. With a single root lockfile, any dependency change for the API also changes the file the web image copies. That invalidates both npm ci layers. If the apps change independently, consider building each image from only the files it needs, or accept that dependency updates rebuild both.
To build both images in one job, Docker Bake can run several targets concurrently, each with its own cache settings. A matrix job with one image per job is a simpler alternative.
Branches and pull requests
GitHub's cache isn't shared freely between branches. Per the dependency caching reference, a run can restore caches created on its own branch or the default branch, but not caches from child or sibling branches. A cache created by a pull request run belongs to the pull request's merge ref, so only re-runs of that pull request can use it.
In practice:
- Run the build on pushes to the default branch, not only on pull requests. That's where the cache every branch can read comes from.
- Expect the first build on a new branch to read from the default branch's cache. Builds get faster once that cache is warm.
- If the default branch rarely builds, its cache can expire after 7 days without access, and the next pull request starts cold.
Don't let the cache hide a stale base image
A warm cache is fast partly because it doesn't re-check much. That includes your base image. If your Dockerfile starts from a tag like a Node.js LTS Alpine image, a cached build can keep using the layers built on an older version of that base, including ones that predate a security fix.
Docker's build best practices give the tools:
- Pin the base image to a digest, so the exact base is explicit in the Dockerfile.
- Let a bot update it. Docker notes that Dependabot can raise pull requests that update base image tags and digests on a schedule. Renovate is a common alternative.
- Use the pull option to check for a newer base image.
- Rebuild regularly without the cache, for example on a weekly schedule, so every layer is rebuilt against current packages.
Combined, these make base image changes visible in code review instead of silent. The earlier post on triaging container image vulnerabilities covers what to do with the scan results.
Keep the cache trustworthy
The cache feeds layers straight into your production image, so treat it as part of your supply chain.
- Know which runs share the default branch's cache. GitHub's secure use reference explains that runs triggered by
pull_request_targetandworkflow_runshare the default branch's cache. GitHub's caching reference says those triggers get read-only access to it by default. Keep it that way, and never build untrusted pull request code in a privileged workflow that can push images or write a registry cache. - Export only from trusted runs. A common pattern: pull request builds only read the cache (
cache-from), while pushes to the default branch read and write it. For a registry cache, limit push rights on the cache repository the same way you limit the image repository. - Keep secrets out of layers and caches. GitHub's caching docs say not to store sensitive information in caches. Pass build secrets, such as a private npm registry token, as BuildKit secrets rather than build arguments or environment variables, so they don't end up in a layer.
The earlier post on securing third-party GitHub Actions covers pinning the actions themselves.
Measure it
Don't assume the cache works. Check it:
- Build summary. Docker's GitHub Actions build summary shows the Dockerfile used, the build duration, and cache utilization in the job summary. It also uploads a build record you can inspect later. You can turn it off with an environment variable if needed.
- Build history. The Buildx CLI includes a history command for listing and inspecting past builds, including imported build records.
- Before and after. Record job duration for a typical source-only change and a lockfile change, before and after the cache setup. Those two cases show whether the layer cache and the npm mount each pay off.
If cache hits stay low, check the order of COPY instructions and the .dockerignore first. They're the most common reasons a layer is invalidated.
Docker also offers Docker Build Cloud, a remote builder with a shared cache, if managing cache backends yourself isn't worth it.
Checklist
- Copy lockfiles before source, run
npm ci, then copy the rest, and keep a strict.dockerignore. - Use multi-stage builds, with
npm ci --omit=devfor the NestJS runtime and a static server for React. - Rely on the layer cache first. Add npm cache mounts, and the CI workaround for them, only if lockfile changes are frequent.
- Use setup-buildx and current action versions, which meet the GitHub cache API v2 minimums.
- Export the cache with
type=ghaor a registry cache, usingmode=maxfor multi-stage builds. - Give each image its own cache scope, and watch the 10 GB repository budget.
- Build on pushes to the default branch so branches have a warm cache.
- Pin base images by digest, let a bot update them, and rebuild without the cache on a schedule.
- Write the cache only from trusted runs, and pass secrets as BuildKit secrets.
- Check the build summary for cache utilization, and compare durations before and after.



