Skip to main content

Containers and Kubernetes · Intermediate · 20 min

Speed up Docker builds with layer caching and cache mounts

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Docker Engine 29.10 with BuildKit · Node.js 26

You will take a slow Dockerfile for a Node.js 26 app, measure its builds, and make rebuilds fast with a smaller build context, a cache-friendly order, an npm cache mount and a build cache your CI can reuse.

On this page

A Docker build that takes three minutes is annoying once. Twenty times a day, across a team and a CI pipeline, it is real time and real bandwidth. Most slow builds come from a few causes that you can see in the build output: a build context full of files the image does not need, instructions in an order that throws the cache away, and package managers that download the same files again on every change.

How to write a Dockerfile for a Node.js app showed one fix: copy the package files before the code. This tutorial goes further. You will start with a deliberately slow Dockerfile, read BuildKit's plain build output to see exactly which steps run, and fix the build one cause at a time, writing down the time after each change. Then you will add a cache mount so dependency changes stop downloading everything, export the build cache for CI, and learn to measure and trim the cache on disk.

Docker Engine 29 builds with BuildKit by default (docker build runs through the Buildx plugin). Every command here runs in a terminal on your computer or build server, in a throwaway folder, ~/cache-demo. Build logs and your timing notes go in a second folder, ~/cache-demo-logs, so that they are not part of what Docker builds from.

Step 1 · Build a slow baseline and time it

Make the demo app. It is a small Express server with a logger, enough dependencies for the install step to take a noticeable moment:

Bash
mkdir -p ~/cache-demo ~/cache-demo-logs
cd ~/cache-demo
npm init -y
npm install express@5.3.0 pino@10.4.0
Bash
cat > server.js <<'JS'
const express = require('express')
const pino = require('pino')

const log = pino()
const app = express()
const port = process.env.PORT || 3000

app.get('/', (req, res) => {
  res.json({ message: 'cache demo', node: process.version })
})

app.listen(port, () => log.info({ port }, 'listening'))
JS

Now write the slow Dockerfile. It copies the whole folder, including the node_modules folder that npm install made on your computer, and then installs again:

Bash
cat > Dockerfile <<'DOCKER'
FROM node:26-slim
WORKDIR /app
COPY . .
RUN npm ci --omit=dev
CMD ["node", "server.js"]
DOCKER

Build it twice: once with --no-cache to time a cold build, and once straight after with no changes. --progress=plain prints every step as text instead of the collapsing progress display, and 2>&1 | tee saves that output to a file in ~/cache-demo-logs, because BuildKit writes its progress to standard error. Keep the logs out of ~/cache-demo: any new or changed file in the build folder is picked up by COPY . . and breaks the cache, which would spoil the no-change rebuild:

Bash
time docker build --no-cache --progress=plain -t cache-demo:slow . 2>&1 | tee ~/cache-demo-logs/build-cold.log
time docker build --progress=plain -t cache-demo:slow . 2>&1 | tee ~/cache-demo-logs/build-warm.log

Open a notes file and write down the real time of each build. Keep these numbers; you will add to them in every step:

Bash
cat > ~/cache-demo-logs/timings.txt <<'TXT'
cold build, slow Dockerfile:            ___ s
rebuild, no changes:                    ___ s
TXT

Your times depend on your machine and your connection. On prepaid mobile data, as many developers in Nigeria and across Africa use, the cold build is also the expensive one: the base image and every npm package come over the network.

Check it worked

docker images cache-demo lists cache-demo with the tag slow. Run grep CACHED ~/cache-demo-logs/build-warm.log and you see a cached line for each of the WORKDIR, COPY and RUN steps, something like #7 [3/4] COPY . . followed by #7 CACHED. The rebuild with no changes is much faster than the cold one, and ~/cache-demo-logs/timings.txt has both numbers in it.

Step 2 · Read the build output to see where the cache breaks

The layer cache is a chain. For each instruction, BuildKit asks: is there a cached result with the same parent layer and the same instruction? For RUN, "the same instruction" means the same command text; BuildKit does not look at what the command would download. For COPY and ADD, it also compares a checksum of the files being copied, built from their contents and metadata, not their modification times. The first instruction that misses is run again, and so is every instruction after it, whether or not they changed.

Two columns of Dockerfile steps after a one-line change to server.js: with COPY . . first, COPY and npm ci both rebuild; with package files first, npm ci is reused and only COPY server.js rebuilds
A miss rebuilds that step and every step below it.

See it for yourself. Change one line of code and rebuild:

Bash
sed -i.bak 's/cache demo/cache demo v2/' server.js && rm server.js.bak
time docker build --progress=plain -t cache-demo:slow . 2>&1 | tee ~/cache-demo-logs/build-edit.log

In build-edit.log, each step starts with a number and a name such as #8 [4/4] RUN npm ci --omit=dev. A step that was reused ends with CACHED. A step that ran shows its own output (here, npm's added ... packages line) and ends with DONE and a time in seconds. Find the first step without CACHED:

Bash
grep -E '^#[0-9]+ (\[|CACHED|DONE)' ~/cache-demo-logs/build-edit.log

Add the time to your notes as code edit, slow Dockerfile.

Check it worked

The COPY . . step is not cached, and neither is RUN npm ci --omit=dev after it: npm reinstalls every package for a one-line code change. Its DONE time is most of the build. That is the cost the next three steps remove.

Step 3 · Shrink the build context with .dockerignore

Before any instruction runs, the client sends the build context (the folder named by the . at the end of the command) to BuildKit. Look for it in the log:

Bash
grep -A3 'load build context' ~/cache-demo-logs/build-edit.log

You see a line such as transferring context: 6.12MB. Almost all of that is your local node_modules. None of it belongs in the image: npm ci deletes node_modules and installs it again, and any file in the context that COPY . . picks up can change the checksum and break the cache, even a stray log file. A .env file with secrets would be copied into the image too.

Write a .dockerignore next to the Dockerfile. It uses the same patterns as .gitignore:

Bash
cat > .dockerignore <<'IGNORE'
node_modules
npm-debug.log
*.log
timings.txt
.git
.env
.env.*
Dockerfile
.dockerignore
IGNORE

Rebuild and look at the context size again:

Bash
docker build --progress=plain -t cache-demo:slow . 2>&1 | tee ~/cache-demo-logs/build-context.log
grep 'transferring context' ~/cache-demo-logs/build-context.log

On a large project, keep an eye on this number over time. Test fixtures, build output folders such as dist/, and coverage reports are common additions to .dockerignore.

Check it worked

The transferring context size drops to a small fraction of what it was (something like tens of kilobytes, most of it the lock file), because only package.json, package-lock.json and server.js are sent. Run docker run --rm cache-demo:slow ls and the list shows those three files plus the node_modules that npm ci built inside the image, and no .log files.

Step 4 · Put the slow steps first and the cache breakers last

Now reorder the Dockerfile so the expensive install depends only on the two files that describe your dependencies. Code changes then reuse the install layer:

Bash
cat > Dockerfile <<'DOCKER'
FROM node:26-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY server.js ./
ARG GIT_SHA=dev
ENV GIT_SHA=$GIT_SHA
ENV NODE_ENV=production
USER node
CMD ["node", "server.js"]
DOCKER

Two other lines in that file are there to make a point about cache breakers:

  • ARG GIT_SHA is a build argument, for example a commit hash your CI passes with --build-arg GIT_SHA=$(git rev-parse --short HEAD). Its value changes on every commit. A changed ARG causes a cache miss where it is first used, not where it is declared, and the miss carries on to every later step. Declare and use per-build values like this near the end, after the install. If you put ARG GIT_SHA at the top and used it in a RUN before npm ci, every commit would reinstall everything.
  • COPY of any file that changes often is also a cache breaker, which is why server.js comes after the install. In a real app, copy the whole source folder at this point, with COPY . . after the install, and let .dockerignore keep the noise out.

Other common breakers to look for in your own Dockerfiles: ADD of a URL, a RUN line that includes a date or random value, and RUN apt-get update in a step of its own (it stays cached for months, so a later apt-get install uses a stale package list; keep update and install in the same RUN).

Build once to fill the cache, then make another code change and time the rebuild:

Bash
docker build --progress=plain -t cache-demo:ordered . 2>&1 | tee ~/cache-demo-logs/build-ordered.log
sed -i.bak 's/cache demo v2/cache demo v3/' server.js && rm server.js.bak
time docker build --progress=plain --build-arg GIT_SHA=abc1234 -t cache-demo:ordered . 2>&1 | tee ~/cache-demo-logs/build-ordered-edit.log
grep -E '^#[0-9]+ (\[|CACHED)' ~/cache-demo-logs/build-ordered-edit.log

Add the time to your notes as code edit, ordered Dockerfile.

Check it worked

In build-ordered-edit.log, the COPY package.json package-lock.json ./ and RUN npm ci --omit=dev steps both show CACHED. Only COPY server.js ./ and the steps after it run. The code-edit time in your notes is now a small fraction of the slow Dockerfile's code-edit time. docker run --rm cache-demo:ordered printenv GIT_SHA prints abc1234.

Step 5 · Keep the npm cache between builds with a cache mount

The order fix helps code changes, but a dependency change still misses the install layer, and npm ci then downloads every package again, not only the one you added. A cache mount fixes that. RUN --mount=type=cache,target=/root/.npm attaches a folder that BuildKit keeps between builds. npm stores downloaded packages there (/root/.npm is npm's cache folder for the root user), so the next install reads most of them from disk.

The npm ci layer is rebuilt when package-lock.json changes, while a cache mount from builder storage supplies /root/.npm; the mount is not part of the image
The layer cache skips a step; a cache mount makes a step that has to run faster.

The cached files never end up in the image: the folder is only attached while that one RUN runs. The build must also work when the folder is empty, because BuildKit may clear it to free space, so a cache mount is a speed-up, never a place to keep anything you need.

Change the install line. The # syntax line at the top asks for the current stable Dockerfile frontend, which supports every --mount option shown here:

Bash
cat > Dockerfile <<'DOCKER'
# syntax=docker/dockerfile:1
FROM node:26-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
    npm ci --omit=dev
COPY server.js ./
ARG GIT_SHA=dev
ENV GIT_SHA=$GIT_SHA
ENV NODE_ENV=production
USER node
CMD ["node", "server.js"]
DOCKER

The install runs as root, before USER node, so /root/.npm is the right target. If you install as another user, set the target to that user's cache folder and give the mount the user's IDs, for example --mount=type=cache,target=/home/node/.npm,uid=1000,gid=1000.

Build once to fill the cache. Then add a dependency, which changes the lock file and forces the install step to run, and time it:

Bash
docker build --progress=plain -t cache-demo:mounted . 2>&1 | tee ~/cache-demo-logs/build-mount-1.log
npm install dotenv@18.0.10
time docker build --progress=plain -t cache-demo:mounted . 2>&1 | tee ~/cache-demo-logs/build-mount-2.log

Write that time down as dependency change, cache mount. For the comparison, make the same kind of change without the mount. Write the previous step's Dockerfile again with its heredoc (the one without --mount), add another small dependency with npm install ms@2.1.3, and time docker build --progress=plain -t cache-demo:ordered .. Record it as dependency change, no cache mount, then write this step's Dockerfile back before you go on.

Other package managers

The same idea works for every package manager that keeps a download cache. These are the usual targets. For apt in Debian and Ubuntu images, first turn off the image's rule that deletes downloaded packages, and lock the mounts, because apt needs exclusive access to its folders:

Dockerfile
RUN rm -f /etc/apt/apt.conf.d/docker-clean; \
    echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
    --mount=type=cache,target=/var/lib/apt,sharing=locked \
    apt-get update && apt-get install -y --no-install-recommends curl

For pip, Go modules and the Go build cache:

Dockerfile
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install -r requirements.txt

RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    go build -o /out/app ./cmd/app

sharing=locked makes a second build that needs the same mount wait for the first. The default, shared, lets builds use it at the same time, which is fine for npm, pip and Go.

Check it worked

In build-mount-2.log, the RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev step is not cached (the lock file changed), but its DONE time is shorter than the same step without the mount, because npm took most packages from the cache. To check that the cache stayed out of the image, run docker run --rm --user root cache-demo:mounted sh -c 'ls /root/.npm/_cacache 2>/dev/null || echo "no npm cache in the image"': it prints something like no npm cache in the image, because npm's package store (_cacache) lives only in the mount. docker run --rm cache-demo:mounted node -e "require('dotenv'); console.log('ok')" prints ok.

Step 6 · Share the layer cache with CI

On your laptop, the cache lives in the builder and survives between builds. A fresh CI runner starts with nothing, so every pipeline run is a cold build. Exporting the build cache fixes that: --cache-to writes it somewhere after a build, and --cache-from reads it at the start of the next.

Two places to keep it:

  • type=registry pushes the cache to a separate image in your container registry, such as ghcr.io/<you>/cache-demo:buildcache (replace <you> with your account name in lower case: image names must be lowercase, and a name such as ghcr.io/AdaObi/... is rejected).
  • type=gha stores it in the GitHub Actions cache, inside GitHub's size limits for your repository.

Add mode=max to --cache-to to export every step, including those of build stages that do not end up in the final image. The default, mode=min, exports only the final image's layers. max gives more cache hits and min is smaller, so less to upload and download; on metered data, try min first.

The default docker builder can export to a registry only when Docker uses the containerd image store, which is the default on fresh Docker Engine 29 installs. If your engine was upgraded from an older version, create a builder that runs BuildKit in its own container instead:

Bash
docker buildx create --name cache-builder --driver docker-container --use

Then build, push and export the cache in one command. Log in to the registry first with docker login ghcr.io, which prompts for your token:

Bash
docker buildx build --push \
  -t ghcr.io/<you>/cache-demo:latest \
  --cache-to type=registry,ref=ghcr.io/<you>/cache-demo:buildcache,mode=max \
  --cache-from type=registry,ref=ghcr.io/<you>/cache-demo:buildcache \
  .

In GitHub Actions, the official Docker actions do the same. The workflow needs the demo in a GitHub repository. Create an empty repository on GitHub called cache-demo, then save the workflow below as .github/workflows/image.yml inside ~/cache-demo. It uses the built-in GITHUB_TOKEN to push to the GitHub Container Registry, so there is no secret to create. Its first step makes a lowercase copy of the repository name, because ghcr.io/${{ github.repository }} fails with a repository name must be lowercase error when the account or repository name has capital letters:

YAML
name: image
on: push
permissions:
  contents: read
  packages: write
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Set a lowercase image name
        run: echo "IMAGE=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV"
      - uses: docker/setup-buildx-action@v4
      - uses: docker/build-push-action@v7
        with:
          context: .
          push: true
          tags: ${{ env.IMAGE }}:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max

Then commit the folder and push it (replace <you> with your GitHub account). The .gitignore keeps your local node_modules out of the repository, and the .dockerignore already keeps .git out of the build context:

Bash
cd ~/cache-demo
printf 'node_modules\n' > .gitignore
git init -b main
git add .
git commit -m "Cache demo with a cached Docker build"
git remote add origin https://github.com/<you>/cache-demo.git
git push -u origin main

If you would rather use a repository you already have, copy Dockerfile, .dockerignore, package.json, package-lock.json, server.js and the workflow file into it and push.

If one repository builds several images, give each its own cache with a scope, for example type=gha,scope=api on both lines, or each build overwrites the other's cache.

Note what this does not carry over: cache mounts. The npm cache mount from the previous step stays in the builder, is not part of the exported cache, and starts empty on every fresh runner. The layer cache still skips the install when the lock file is unchanged, which is the common case. If you need the mount contents in CI too, Docker's documentation points to a third-party action that copies them in and out of the GitHub cache.

Check it worked

Change only server.js, commit and git push, twice. In the second run's log for the build step, the npm ci step shows CACHED, and the run is faster than the first. Under the repository's Actions tab, the caches page lists one or more entries created by BuildKit.

Step 7 · Measure and clean up the build cache

Caches take disk space, and on a small server or a laptop with a nearly full disk that matters. The cache from steps 1 to 5 belongs to the default builder. If you ran docker buildx create ... --use in the CI step, cache-builder is now your current builder, and du and prune would act on it instead. Switch back first, and name the builder on each command so there is no doubt:

Bash
docker buildx use default
docker buildx du --builder default

The output lists cache records with an ID, whether each is reclaimable, its size and when it was last used, and ends with totals: Shared, Private, Reclaimable and Total. Write down the Total. Cache mounts appear in this list too. docker buildx du --builder default --verbose shows what each record is, such as the step that made it.

The routine clean-up on a build machine removes records you have not used for a week:

Bash
docker buildx prune --builder default --filter until=168h

It asks for confirmation and prints what it frees. Today that is nothing, or close to it, because every record you made in this tutorial is newer than a week. Keep the command for a cron job or a monthly habit.

To see a prune that does free space now, remove only the cache mounts, such as the npm cache from the cache mount step. The type filter picks out that kind of record:

Bash
docker buildx prune --builder default --filter type=exec.cachemount
docker buildx du --builder default

The image layers stay, so a code edit still rebuilds quickly; the next dependency change downloads every package again and fills the mount once more.

To cap the cache instead, keep the most recently used records and remove the rest until it fits a size, for example 10 GB:

Bash
docker buildx prune --builder default --max-used-space 10gb

On a cache smaller than the limit, as yours is now, it frees nothing. docker buildx prune --builder default --all removes every unused cache record, which makes the next build a cold one. Run it when you want to reclaim everything, not as a routine.

When you are done, remove what this tutorial made: the images, the extra builder (if you created one) and the two demo folders. docker buildx rm deletes the builder and its cache:

Bash
docker rmi cache-demo:slow cache-demo:ordered cache-demo:mounted
docker buildx rm cache-builder
rm -rf ~/cache-demo ~/cache-demo-logs

If you pushed to a registry, delete the cache-demo package there too, from your registry's package settings.

Check it worked

The until=168h prune frees little or nothing, as expected for a cache made today. After the type=exec.cachemount prune, docker buildx du --builder default shows a lower Total than the one you wrote down, by roughly the size of the npm cache, and no records from the cache mount. After the clean-up, docker images cache-demo lists nothing, and docker buildx ls no longer shows cache-builder. Before you deleted the folders, timings.txt held a before-and-after record of each change; keep a copy of it if you want to make the same case for your own project.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.