Sub topic 6
Pruning the build cache
This chapter covers the build cache: what it holds, how to see its size, and how to remove it with docker builder prune. It assumes you can run docker build, know that an image is made of layers, and have read the chapters on docker system df and on dangling images.
What the build cache is
When you run docker build, Docker runs each Dockerfile instruction as a step. It saves the result of each step so that an identical step can be reused next time. Those saved results are the build cache. A step is reused when the instruction and everything it depends on are unchanged. For COPY and ADD, that includes the content of the copied files.
With BuildKit, the default builder in current Docker releases, the cache is stored separately from your images. That has two consequences:
- Removing an image does not remove the cache that built it.
docker image prunedoes not touch the cache, even with-a.
Cache entries accumulate quietly. Each time a step's input changes, for example COPY . . after you edit a source file, BuildKit stores a new result and keeps the old one. A project rebuilt many times a day can pile up gigabytes this way. Build servers and CI runners are the usual victims.
The cache also includes data that is not an image layer at all. Examples are downloaded base-image content, files fetched by ADD <url>, and cache mounts (RUN --mount=type=cache) that tools like package managers use to keep their download directories.
Seeing how much cache you have
docker system df reports build cache as its own row:
docker system dfTypical output looks like this:
TYPE TOTAL ACTIVE SIZE RECLAIMABLE
Images 14 5 6.2GB 4.1GB (66%)
Containers 7 2 120MB 95MB (79%)
Local Volumes 9 3 1.8GB 900MB (50%)
Build Cache 212 0 9.4GB 9.4GBRead the Build Cache row like this:
TOTALcounts cache records, not images.ACTIVEcounts records in use by a build running right now. It is normally 0 when nothing is building.RECLAIMABLEis what a prune could free. For the cache this is often the full size, because nothing references old records.
To see each record, add -v:
docker system df -vThe build cache section lists each record's ID, type, size, creation time, last-used time, and use count. Records with an old last-used time and a use count of 1 are good candidates for removal, because they were built once and never reused.
If you use buildx with several builders, each builder has its own cache. docker buildx du shows the cache for the current builder:
docker buildx duRemoving the cache
The command is docker builder prune:
docker builder pruneIt prints a warning and asks for confirmation. When it finishes, it prints the reclaimed total, such as Total: 3.2GB.
Without -a, the command removes only cache records that Docker considers dangling. In practice that is a smaller set than "everything not in use". To remove all cache that no running build is using, add -a (--all):
docker builder prune -aUse -f (--force) to skip the prompt, as in scripts:
docker builder prune -a -fThe same operation exists under buildx, and it acts on the current builder:
docker buildx pruneA related command from the earlier chapters, docker system prune, also removes unused build cache along with stopped containers, unused networks, and dangling images. Use docker builder prune when you want to clear the cache and nothing else.
What you give up
Pruning the cache never deletes images, containers, or volumes. Its cost is time. The next build has to redo every step it can no longer find in the cache. That means:
- Re-downloading base images.
- Re-running
apt-get install,npm ci,pip install, and similar steps. - Recompiling anything compiled during the build.
For a large project the first build after a full prune can take many minutes instead of seconds. On a developer laptop that is usually acceptable. On a CI runner that builds all day, a full prune on every run defeats the cache. The sections below show how to keep the useful part.
Keeping recent cache with filters
The until filter keeps records newer than a given age and removes the rest. This frees stale entries while preserving the cache for the work you are doing now:
docker builder prune --filter "until=168h"Here 168h is seven days. The filter accepts Go duration strings such as 24h or 72h30m, and it also accepts timestamps. Combine it with -a and -f for a script-friendly form:
docker builder prune -a -f --filter "until=168h"Some Docker versions also let you cap the cache size instead of its age. In older releases the flag is --keep-storage, and in newer ones it is --reserved-space. It keeps up to the given amount of the most recently used cache and removes the rest:
docker builder prune --keep-storage 5GBCheck docker builder prune --help on your machine to see which flag your version has. A size cap suits CI runners well. The cache stays warm for common builds, and the disk use stays bounded.
| Goal | Command |
|---|---|
| Remove only dangling cache | `docker builder prune` |
| Remove all unused cache | `docker builder prune -a` |
| Remove cache older than 7 days | `docker builder prune -a --filter "until=168h"` |
| Keep about 5 GB of recent cache | `docker builder prune --keep-storage 5GB` |
| Skip the confirmation prompt | add `-f` to any of the above |
Previewing a cache prune
docker builder prune has no dry-run flag. To estimate what it will free, compare two numbers:
- Run
docker system dfand note theRECLAIMABLEvalue on theBuild Cacherow. - Run
docker system df -vand scan the build cache list for old records.
The reclaimable figure is an upper bound for -a. A filtered prune frees less, because records newer than the cutoff stay. Run the prune and compare the Total: line with your estimate.
Why the cache keeps growing
If you prune and the cache is back to many gigabytes a week later, look at how your builds produce new records:
- Copying the whole project early in the Dockerfile. Any edit invalidates that step and every step after it, and each rebuild stores a full new set. A
.dockerignorefile and a better step order shrink this. - Frequent base image updates. Each new digest of a tag like
node:20brings new layers. - Cache mounts that grow without bound, for example a package manager's download directory. Pruning with
-aclears them, and a size cap limits them. - Many branches or CI jobs sharing one builder. Every branch leaves its own records.
Here is a Dockerfile ordered to limit churn. Dependencies are copied and installed first, so the expensive install step stays cached until package.json changes:
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
CMD ["node", "dist/server.js"]If you edit only a source file, BuildKit reuses the npm ci result and stores new records only for the last COPY and RUN steps.
Common errors
- Space does not come back after
docker image prune -a. The cache is separate from images under BuildKit. Rundocker builder pruneas well. - The prune frees less than
RECLAIMABLEsuggested. You probably ran it without-a, or you used a filter that kept recent records. - Disk usage stays high on a machine with several builders.
docker builder pruneacts on the current builder. List builders withdocker buildx ls, then prune each one withdocker buildx prune --builder <name>. - The next build is very slow. That is expected after a full prune. The cache rebuilds as you build.
Exercise
A CI runner builds an image on every push. Its disk is filling up because of the build cache, but a full cache wipe makes every build slow. Which command removes cache that has not been used in the last seven days, with no confirmation prompt, and why is it a better fit than docker builder prune -a -f?
Show answer
Use docker builder prune -a -f --filter "until=168h". The until=168h filter keeps records newer than seven days, so builds for active branches still reuse cached steps, while old records that nothing has used are removed. -a includes all unused records, not just dangling ones, and -f skips the prompt for scripts. Without the filter, docker builder prune -a -f deletes every unused record and forces the next build to redo every step.
Exercise
You run docker image prune -a and then docker system df. The Images row has shrunk, but Build Cache still shows 9 GB reclaimable. Why, and what do you run next?
Show answer
Under BuildKit, the build cache is stored separately from images, so image pruning does not touch it. Run docker builder prune -a (add -f to skip the prompt, and --filter "until=<age>" to keep recent records), then check docker system df again.