TExcelTAD
Home › Docker › Building & the Build Cache

Building & the Build Cache

Docker builds are fast on the second run because of the build cache. Before executing an instruction, the builder checks whether it already has a layer produced by the same instruction on top of the same parent layer, with the same input files. If so, it reuses that layer (CACHED in the build log) instead of running the step again.

text
 => CACHED [2/6] WORKDIR /app                                   0.0s
 => CACHED [3/6] COPY requirements.txt .                        0.0s
 => CACHED [4/6] RUN pip install -r requirements.txt            0.0s
 => [5/6] COPY . .                                              0.1s
 => [6/6] RUN python -m compileall .                            0.6s

The cache rules

Instruction Cache hit when
RUN parent layer is the same and the command text is identical
COPY / ADD parent is the same and the checksums of the copied files match (timestamps are ignored)
ENV, ARG, WORKDIR, … parent is the same and the instruction text is identical (an ARG value that a later step uses counts too)

And the most important rule: once one step misses the cache, every later step is rebuilt, because their parent layer changed.

Note what RUN does not check: RUN apt-get install -y curl hits the cache even if a newer curl was released yesterday, because Docker only compares the command text.

A layer-cache simulator

Each layer gets a cache key: a hash of the parent key, the instruction, and (for COPY) the content of the files it copies. Change one file and watch which steps rebuild.

python · try it yourself
import hashlib

def h(*parts):
    return hashlib.sha256("|".join(parts).encode()).hexdigest()[:10]

cache = set()

def build(steps, files, label):
    print(f"--- {label}")
    parent, missed = "base", False
    for step in steps:
        inputs = ""
        if step.startswith("COPY"):
            src = step.split()[1]
            chosen = sorted(f for f in files if src == "." or f == src)
            inputs = h(*(f + files[f] for f in chosen))
        key = h(parent, step, inputs)
        status = "CACHED" if key in cache and not missed else "BUILD "
        missed = missed or status == "BUILD "
        cache.add(key)
        print(f"  {status} {step}")
        parent = key

steps = [
    "WORKDIR /app",
    "COPY requirements.txt .",
    "RUN pip install -r requirements.txt",
    "COPY . .",
    "CMD python app.py",
]
files = {"requirements.txt": "flask==3.1.1", "app.py": "v1", "util.py": "v1"}

build(steps, files, "first build")
build(steps, files, "rebuild, nothing changed")
files["app.py"] = "v2"
build(steps, files, "edited app.py")
files["requirements.txt"] = "flask==3.1.1\nredis==6.2.0"
build(steps, files, "added a dependency")
--- first build
  BUILD  WORKDIR /app
  BUILD  COPY requirements.txt .
  BUILD  RUN pip install -r requirements.txt
  BUILD  COPY . .
  BUILD  CMD python app.py
--- rebuild, nothing changed
  CACHED WORKDIR /app
  CACHED COPY requirements.txt .
  CACHED RUN pip install -r requirements.txt
  CACHED COPY . .
  CACHED CMD python app.py
--- edited app.py
  CACHED WORKDIR /app
  CACHED COPY requirements.txt .
  CACHED RUN pip install -r requirements.txt
  BUILD  COPY . .
  BUILD  CMD python app.py
--- added a dependency
  CACHED WORKDIR /app
  BUILD  COPY requirements.txt .
  BUILD  RUN pip install -r requirements.txt
  BUILD  COPY . .
  BUILD  CMD python app.py

Editing app.py only re-runs the cheap COPY . .; the slow pip install stays cached. Only changing requirements.txt re-installs the dependencies.

Order matters

Put things that change rarely first and things that change often last. Here is the same simulator with the classic mistake, copying all the source before installing dependencies:

python · try it yourself
import hashlib

def h(*parts):
    return hashlib.sha256("|".join(parts).encode()).hexdigest()[:10]

COST = {"RUN pip install -r requirements.txt": 45.0}

def rebuild_seconds(steps, before, after):
    cache, total = set(), 0.0
    for files, record in ((before, False), (after, True)):
        parent, missed = "base", False
        for step in steps:
            inputs = ""
            if step.startswith("COPY"):
                src = step.split()[1]
                inputs = h(*(f + files[f] for f in sorted(files) if src == "." or f == src))
            key = h(parent, step, inputs)
            miss = missed or key not in cache
            missed = miss
            cache.add(key)
            if record and miss:
                total += COST.get(step, 0.2)
            parent = key
    return total

before = {"requirements.txt": "flask", "app.py": "v1"}
after = {"requirements.txt": "flask", "app.py": "v2"}      # a one-line code change

good = ["COPY requirements.txt .", "RUN pip install -r requirements.txt", "COPY . ."]
bad = ["COPY . .", "RUN pip install -r requirements.txt"]

print(f"deps first : rebuild after code edit takes {rebuild_seconds(good, before, after):5.1f}s")
print(f"copy all   : rebuild after code edit takes {rebuild_seconds(bad, before, after):5.1f}s")
deps first : rebuild after code edit takes   0.2s
copy all   : rebuild after code edit takes  45.2s

The same pattern applies to every ecosystem: package.json + package-lock.json then npm ci; go.mod + go.sum then go mod download; pom.xml then mvn dependency:go-offline; Cargo.toml + Cargo.lock.

Controlling the cache

bash
docker build -t shop .                      # use the cache
docker build --no-cache -t shop .           # rebuild every step
docker build --pull -t shop .               # also check for a newer base image
docker builder prune                        # delete build cache

BuildKit adds cache mounts, which keep a package manager's download cache between builds without putting it in the image:

dockerfile
# syntax=docker/dockerfile:1
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install -r requirements.txt

Even when requirements.txt changes and the step must re-run, pip finds the wheels it downloaded last time in the cache mount.

In CI, where each build starts on a fresh machine, export and import the cache with --cache-to and --cache-from (for example to a registry or the GitHub Actions cache); see Docker in CI/CD.

Tip: a small source change that makes the build slow again is a sign that a COPY near the top of your Dockerfile copies too much. Narrow it, or add a .dockerignore.

Test yourself

A Dockerfile has 6 steps. Step 3 misses the cache. Which steps are rebuilt?

  1. Only step 3
  2. Steps 3, 4, 5 and 6
  3. All 6 steps
  4. Steps 1 to 3

How does the builder decide whether a COPY step can use the cache?

  1. It compares file modification times
  2. It compares checksums of the copied files' contents (and the parent layer)
  3. It always rebuilds COPY
  4. It compares file names only

RUN apt-get install -y curl was cached last month. A security fix for curl came out. What does a normal rebuild do?

  1. Installs the new curl automatically
  2. Reuses the cached layer with the old curl, because the command text did not change
  3. Fails
  4. Asks you