Home DockerDocker BuildKit Cache: Faster Image Builds, Step by Step

Docker BuildKit Cache: Faster Image Builds, Step by Step

by Knowledge Base Linux
Docker BuildKit cache

Slow Docker builds waste developer time and CI minutes, and the usual culprit is a cache that never hits. A Docker BuildKit cache, used correctly, reuses unchanged layers instead of rebuilding them, so a small code change rebuilds only the last steps of your image. This guide explains how the Docker BuildKit cache works, how to structure a Dockerfile so the cache survives, and how to share the cache between machines and CI runners.

You will learn the difference between the local layer cache, inline cache, and registry cache, when each one makes sense, and which mistakes silently invalidate the cache on every build. The examples use a Node.js application, but the same principles apply to Python, Go, and Java images.

Docker BuildKit cache illustration

Prerequisites for Using the Docker BuildKit Cache

You need Docker Engine 23 or newer with BuildKit enabled, which is the default on current installs. Confirm it with docker buildx version and docker info. You also need a Dockerfile you control and, for the registry examples, access to a container registry where you can push images.

BuildKit is the modern builder behind docker build on recent Docker versions. If your system still uses the legacy builder, set DOCKER_BUILDKIT=1 or create a buildx builder. The commands in this guide use docker buildx build explicitly, so they work the same on a laptop and in CI.

How the Docker BuildKit Cache Works

BuildKit caches each Dockerfile instruction as a layer, keyed by its inputs: the instruction text, the base image, and the files copied into that step. If nothing changed for a step, BuildKit reuses the cached layer and skips the work. If any input changed, that layer and every layer after it must run again.

This ordering rule is why Dockerfile structure matters so much. A step that copies your entire source tree early in the file invalidates everything below it on every commit, even if only one file changed. A step that installs dependencies before copying source code keeps the expensive install layer cached across code changes.

BuildKit also supports cache mounts and cache backends. A cache mount keeps a directory, such as a package manager cache, alive between builds without baking it into the image. A cache backend exports the cache to a registry or local directory so another machine can import it.

Step 1: Order Your Dockerfile for Maximum Cache Hits

Put the least-changing steps first and the most-changing steps last. For a Node.js application, copy only the dependency manifests, install dependencies, and only then copy the rest of the source code:

# syntax=docker/dockerfile:1
FROM node:22-bookworm-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
RUN npm run build
CMD ["node", "dist/index.js"]

With this order, editing application code reruns only the final copy and build steps. The npm ci layer stays cached as long as the manifests are unchanged. The same pattern works for Python: copy requirements.txt, run pip install, then copy the code. For Go, download modules before copying source.

Avoid copying secrets or large unrelated files into the build context. Add .git, node_modules, test fixtures, and local environment files to .dockerignore so they never become cache inputs:

.git
node_modules
.env
*.log
coverage/

Step 2: Use Cache Mounts for Package Managers

Even with good layer ordering, a dependency install still downloads every package when the lock file changes. A BuildKit cache mount preserves the package manager cache across builds, so only new or changed packages are downloaded:

# syntax=docker/dockerfile:1
FROM node:22-bookworm-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
    npm ci --omit=dev
COPY . .
RUN npm run build
CMD ["node", "dist/index.js"]

The cache mount is not part of the final image, so it does not bloat the image or leak cached credentials. For Python, mount the pip cache directory instead: --mount=type=cache,target=/root/.cache/pip. For apt, mount /var/cache/apt and /var/lib/apt/lists together with apt-get update in the same RUN step.

Step 3: Share the Docker BuildKit Cache in CI

A local cache does not help a fresh CI runner, because every job starts empty. Export the cache to your registry with cache-to and import it on the next run with cache-from. The registry cache backend stores cache metadata alongside your image:

docker buildx create --use --name ci-builder
docker buildx build \
  --cache-from type=registry,ref=registry.example.com/app:buildcache \
  --cache-to type=registry,ref=registry.example.com/app:buildcache,mode=max \
  --tag registry.example.com/app:latest \
  --push .

Use mode=max when you want intermediate layers cached, not just the final image layers. It uses more registry storage but gives much higher hit rates for multi-stage builds. If your registry does not support the cache backend, use the inline cache instead: build with --build-arg BUILDKIT_INLINE_BUILD_CACHE=1 and import with --cache-from pointing at the previous image tag.

For GitHub Actions, the official cache action combined with buildx cache exports is simpler than managing registry tags by hand. Keep the cache scoped per branch where possible, so a feature branch does not evict the main branch cache.

Step 4: Measure and Verify Cache Hits

Do not guess whether the cache works; read the build output. BuildKit prints CACHED next to reused steps. Run the same build twice and compare timings, then change one source file and rebuild to confirm only the later steps rerun:

docker buildx build -t app:test . 2>&1 | grep -E 'CACHED|DONE'
time docker buildx build -t app:test .

If every step reruns, check for a changing input: a COPY . . before the install step, a build argument that changes each run such as a timestamp, or a missing .dockerignore entry that pulls in a changing file. Pin the base image by digest for reproducible builds, and record the digest in your release notes when you upgrade it deliberately.

Troubleshooting Docker BuildKit Cache Problems

The most common problem is a cache that never hits in CI. The cause is usually a fresh builder on every run without cache-from, or a docker buildx create step that discards the previous builder. Create the builder once per job, pass the same cache references every time, and keep the builder name stable.

Another common problem is a cache that hits when it should not. This happens when a step downloads a “latest” package without a lock file, so BuildKit reuses a stale layer while the upstream package moved on. Lock files exist to prevent exactly this: commit them, and bump them deliberately when you want an upgrade.

If the registry cache grows without bound, prune old cache tags on a schedule and prefer mode=min for branches that rarely rebuild. Check build disk usage with docker buildx du and prune with docker buildx prune on self-hosted runners.

Conclusion

A Docker BuildKit cache turns slow, repetitive builds into fast, incremental ones, but only if your Dockerfile is ordered for it: dependencies before source, lock files committed, cache mounts for package managers, and a shared cache backend in CI. Measure cache hits after every change to the Dockerfile, because one misplaced COPY can undo all of it. For related container workflows, see our guides on Docker Buildx multi-architecture images and scanning images with Trivy. The official Docker build cache documentation covers every cache backend in detail.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.