All guides

Docker build cache: order the layers and reuse them in CI

Docker reuses a layer only while the instruction and the files it depends on are unchanged, and once one layer changes, every layer after it is rebuilt. Order the Dockerfile around that rule, then give CI builders a cache they can import.

A desk with two monitors showing code

How the cache decides

The builder goes through the Dockerfile one instruction at a time and checks whether the build cache already holds a result it can reuse. Docker documents these rules:

  • With ADD, COPY and RUN --mount=type=bind, file metadata is the input to the cache checksum the builder computes. A change in that metadata on any file involved invalidates the cache. The modification time (mtime) is not taken into account.
  • For other instructions, the files in the container are not examined. For RUN apt-get -y update, the builder matches on the command string alone.
  • After an invalidation, every later instruction runs again with no use of the cache.

Dependencies before source

These are the opening instructions of a Node.js example in Docker's GitHub Actions documentation:

Dockerfile

# syntax=docker/dockerfile:1
FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .

The package files are copied and the dependencies installed before COPY . . brings in the rest of the project. Docker's cache page explains why. With COPY . . first, updating any file causes a reinstall of all dependencies. With the dependencies installed in earlier layers, those layers are not rebuilt when a project file changes.

Keep the build context small as well. The same page says a small context reduces the likelihood of cache invalidation, and it names a .dockerignore file in the root of the context as the way to get one.

Cache mounts for package managers

A cache mount gives a RUN instruction a persistent cache location. The cache is cumulative across builds, so when the layer is rebuilt, only new or changed packages are downloaded:

Dockerfile

FROM node:latest
WORKDIR /app
RUN --mount=type=cache,target=/root/.npm npm install

/root/.npm is the default location of the npm cache. Targets for other tools: /go/pkg/mod and /root/.cache/go-build for Go, and /root/.cache/pip for pip. The apt example adds sharing=locked, because apt needs exclusive access to its data.

A build should work with any contents of the cache directory. And cache mounts live in the builder's local storage. The cache exported with --cache-to leaves them out, and on a CI runner that gets a fresh machine for each job they are empty at the start of every build.

External caches in CI

The default cache is internal to the builder, and each builder uses its own cache storage. An external cache is a remote location for cache data. --cache-to exports the build cache to it, and --cache-from names the remote caches a build can use.

The registry backend puts the cache in a separate image:

Shell

docker buildx build --push -t <registry>/<image> \
  --cache-to type=registry,ref=<registry>/<cache-image>,mode=max \
  --cache-from type=registry,ref=<registry>/<cache-image> .

The default mode, min, caches only the layers exported into the resulting image. In max mode, all layers are cached, including those of intermediate steps. The ref must differ from the location you push the image to. If the --cache-from target does not exist, the import step fails and the build continues.

On GitHub Actions, the gha backend uploads the cache to the GitHub Actions cache. Docker's backends page labels it beta. This is the workflow from the documentation:

YAML

name: ci

on:
  push:

jobs:
  docker:
    runs-on: ubuntu-latest
    steps:
      - name: Login to Docker Hub
        uses: docker/login-action@v4
        with:
          username: ${{ vars.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v4

      - name: Build and push
        uses: docker/build-push-action@v7
        with:
          push: true
          tags: user/app:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max

user/app:latest is the documentation's image name. Replace it with your own. The action fills in the cache url and token parameters. Four documented details:

  • The scope parameter defaults to buildkit. If you build multiple images, each build overwrites the cache of the previous one, so give each image its own scope.
  • A workflow can read three caches: its current branch's, the base branch's and the default branch's.
  • Events such as pull_request_target, when they run in the context of the default branch, get read-only access to the cache by default. For those workflows, keep cache-from: type=gha and omit cache-to.
  • The default docker driver supports the registry and gha backends only when the containerd image store is enabled. If it is not, use a different driver.

What invalidates a cache

  • An instruction that no cached layer matches exactly, and every instruction after it.
  • A change to the metadata of a file used by ADD, COPY or a bind mount.
  • A different value for a build argument, from the first use of the ARG variable. All RUN instructions that follow an ARG instruction use it implicitly.
  • A different SOURCE_DATE_EPOCH, for WORKDIR and all subsequent instructions.

Two things do not invalidate it. A new value for a build secret does not, since the build cache does not include what build secrets contain. The passing of time does not either: Docker's example is RUN apk add curl, which gets the same packages when the image is rebuilt one week later.

Where to start

  1. Put the instructions that change least first and the ones that change most last, with the dependency install above the COPY of the source.
  2. Add a .dockerignore file and cache mounts for the package manager.
  3. In CI, export the cache with cache-to and import it with cache-from.
  4. Force a RUN instruction to run again when you need newer packages. Docker lists three ways: change a layer before it, clear the build cache with docker builder prune, or use the --no-cache or --no-cache-filter options.

Sources

Want a second pair of eyes on yours? We do this work for a living.

Book a call

More guides