Skip to content

Lesson 13 of 24Building images well

BuildKit, Cache Mounts and Advanced Multi-Stage Builds

Use BuildKit the way platform teams do: cache mounts, bind and SSH mounts, remote CI cache, parallel stages, build checks and Bake.

18 min read0/4 questions

Your layer ordering is perfect, yet CI still spends four minutes on every build. Two things are going on. Every CI runner starts with an empty cache, so the ordering you tuned locally buys nothing there. And whenever uv.lock changes by a single line, the dependency layer misses and the package manager downloads all 300 MB again, because the layer cache is all or nothing. BuildKit has answers to both, plus features that make a Dockerfile cheaper to run in CI and easier to review. This lesson builds on Image Layers and the Build Cache and on the multi-stage basics from Dockerizing a Full-Stack App.

BuildKit, buildx and the syntax line

Three names, one system:

  • BuildKit is the build engine. It has been the default for docker build since Docker Engine 23, so DOCKER_BUILDKIT=1 is no longer needed anywhere.
  • Buildx is the CLI plugin that drives BuildKit. docker build is now an alias for docker buildx build, so every flag in this lesson works with either spelling.
  • A builder is a running BuildKit instance with a driver: docker (built into the daemon, the default), docker-container (BuildKit in its own container, needed for some features on older engines), remote, or cloud (Docker Build Cloud). docker buildx ls lists yours.

The first line of a modern Dockerfile is a parser directive:

# syntax=docker/dockerfile:1

It tells BuildKit to fetch the latest 1.x Dockerfile frontend (the part that turns your Dockerfile into a build graph) from Docker Hub. Without it you get whatever frontend shipped inside your engine, which on an older CI host may not understand heredocs or newer mount options. With it, new syntax works the same on every engine. Teams that need fully pinned builds pin a minor version or a digest instead.

Builds are graphs, not scripts

The frontend converts your Dockerfile into a dependency graph called LLB. BuildKit then solves the graph: it works backwards from the stage you asked for, skips stages nothing depends on, and runs independent stages in parallel. The old builder walked every stage top to bottom, one at a time, even ones the final image never used.

What BuildKit runs for each --target
uv: FROM astral uv imageuvFROM astral uv imagebase: python:3.13-slimbasepython:3.13-slimassets: node: build CSS/JSassetsnode: build CSS/JSdeps: uv sync, 40 sdepsuv sync, 40 stest: + pytest, runs the suitetest+ pytest, runs the suiteprod: final runtime imageprodfinal runtime image

docker build --target prod . BuildKit starts from the requested stage and walks its inputs backwards.

1/4

This model computes the same thing: which stages each target needs, and how long the build takes when independent stages overlap.

Pythonstage_graph.py
from functools import cache # stage -> (seconds of work, stages it reads from)stages = { "uv": (2, []), # FROM ghcr.io/astral-sh/uv "base": (3, []), # FROM python:3.13-slim "deps": (40, ["base", "uv"]), # uv sync --no-install-project "test": (55, ["deps"]), # adds pytest, runs the suite "assets": (35, []), # node stage: builds CSS/JS "prod": (4, ["deps", "assets"]), # final runtime image} def needed(target: str) -> set[str]: out = {target} for dep in stages[target][1]: out |= needed(dep) return out @cachedef finish(stage: str) -> int: seconds, deps = stages[stage] return seconds + max((finish(d) for d in deps), default=0) for target in ["prod", "test"]: need = needed(target) skipped = sorted(set(stages) - need) serial = sum(stages[s][0] for s in need) print(f"--target {target}") print(f" builds: {sorted(need)}") print(f" skips: {skipped}") print(f" one at a time: {serial}s, in parallel: {finish(target)}s")
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

stages = {
  "base": [],
  "deps": ["base"],
  "lint": ["deps"],
  "test": ["deps"],
  "assets": [],
  "prod": ["deps", "assets"],
}

def needed(target):
  out = {target}
  for dep in stages[target]:
      out |= needed(dep)
  return out

print(sorted(needed("test")))
print(len(stages) - len(needed("prod")))
Need a nudge? Hints walk you through it.

Cache mounts: keep the package manager's cache

The layer cache answers "has this exact step run before?" When the answer is no, the step starts from nothing. A cache mount is different: it is a directory that BuildKit keeps between builds and mounts into a RUN step. Point it at your package manager's download cache, and a changed lockfile only downloads what is new.

Dockerfile
# syntax=docker/dockerfile:1
FROM python:3.13-slim AS deps
COPY --from=ghcr.io/astral-sh/uv:0.13.5 /uv /uvx /bin/
ENV UV_LINK_MODE=copy UV_COMPILE_BYTECODE=1
WORKDIR /app
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --locked --no-install-project --no-dev

UV_LINK_MODE=copy is there because the cache mount and /app/.venv are on different filesystems, so uv cannot hard-link and would warn. The same pattern for other ecosystems:

ToolCache mount target
uv/root/.cache/uv
pip/root/.cache/pip
npm/root/.npm
Go/go/pkg/mod and /root/.cache/go-build

With a cache mount you no longer need pip install --no-cache-dir or UV_NO_CACHE: the cache directory is a mount, so nothing written there lands in the layer.

Pythoncache_mount.py
# Package name -> size in MB. Each build uses one version of uv.lock.locks = [ {"fastapi": 2, "pydantic-core": 6, "numpy": 18, "pandas": 14, "sqlalchemy": 4}, {"fastapi": 2, "pydantic-core": 6, "numpy": 18, "pandas": 14, "sqlalchemy": 4, "httpx": 1}, {"fastapi": 2, "pydantic-core": 6, "numpy": 18, "pandas": 14, "sqlalchemy": 4, "httpx": 1, "boto3": 9},] def build_all(use_cache_mount: bool) -> None: download_cache: dict[str, int] = {} # lives in the builder, not the image for n, lock in enumerate(locks, 1): if use_cache_mount: fetch = {p: mb for p, mb in lock.items() if p not in download_cache} else: fetch = dict(lock) # layer missed: start from nothing download_cache.update(fetch) print(f" build {n}: downloaded {sum(fetch.values()):>2} MB {sorted(fetch)}") print("layer cache only")build_all(use_cache_mount=False)print("layer cache + cache mount")build_all(use_cache_mount=True)
Output
Press Run (⌘ Enter) to see what happens.

apt needs two extra moves

Debian and Ubuntu base images ship a config file, /etc/apt/apt.conf.d/docker-clean, that deletes downloaded packages after every install to keep layers small. With a cache mount that is exactly wrong, so remove it. And apt refuses to share its lists and archives between concurrent runs, so lock the mount:

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 gcc

sharing decides what happens when two builds use the same cache at once: shared (the default) lets them both write, private gives the second one a fresh empty copy, and locked makes the second wait.

What cache mounts are not

  • Not in the image. The mount exists only while that RUN runs. Nothing in it ships.
  • Not in the exported cache. Registry and GitHub Actions cache backends export layers, not cache mounts. A fresh CI runner starts with empty cache mounts unless you add a workaround (the Docker docs point to the buildkit-cache-dance action for GitHub Actions).
  • Not guaranteed. BuildKit may garbage-collect the cache, and another build may overwrite files in it. Your build must work with an empty cache. Never store something there that a later step needs.
Quick check
You add --mount=type=cache,target=/root/.cache/uv to the dependency step. Your CI runners are fresh VMs every run, with a registry cache configured (mode=max). On a run where uv.lock changed, what does the cache mount save you?
Need a nudge? A hint rules out a wrong answer.

Bind mounts and SSH mounts

In the uv example, uv.lock and pyproject.toml were bind-mounted from the build context instead of copied. A bind mount is visible only during that RUN and is read-only by default (rw allows writes, which are thrown away). Nothing is stored in a layer, yet BuildKit still checksums the mounted files for the cache key, so editing the lockfile still triggers the step. Bind mounts can also read from another stage: --mount=type=bind,from=build,source=/wheels,target=/wheels installs wheels from a build stage without a COPY layer that you then cannot delete.

Private Git dependencies are the classic place where people leak keys into images. Use an SSH mount, which forwards your SSH agent for one step:

RUN --mount=type=ssh uv sync --locked --no-dev
docker build --ssh default -t api:dev .

--ssh default forwards the agent from SSH_AUTH_SOCK. The key never enters the build: only the agent socket does, for that one step. Git also needs the host key, so add the server to known_hosts first (ssh-keyscan github.com) or the clone hangs at the prompt. Token secrets use --mount=type=secret, covered in Docker in Production.

Remote cache for CI

Every hosted CI runner starts with an empty builder. To reuse layers across runs, export the cache somewhere at the end of a build and import it at the start of the next:

docker buildx build --cache-from type=registry,ref=ghcr.io/acme/api:buildcache --cache-to type=registry,ref=ghcr.io/acme/api:buildcache,mode=max -t ghcr.io/acme/api:sha-7f3c2a1 --push .
A fresh CI runner with a registry cache
RunnerBuildKitRegistrybuild --cache-from ...:buildcachefetch cache manifestkeys for 9 stepspull blobs only for hitspush image + new cache

The runner's local cache is empty, as on every hosted runner.

1/5

The backends you will meet:

BackendWhere the cache goesUse it when
inlineInside the image itselfSimple single-stage builds; only final-stage layers, min mode only
registryA separate image ref, such as :buildcacheThe default choice for any registry-backed CI
ghaThe GitHub Actions cache serviceGitHub-hosted runners, small to medium images
localA directorySelf-managed runners with a persistent disk

mode=min (the default) exports only layers that end up in the final image. mode=max exports every layer of every stage. For multi-stage builds, max is what makes the expensive deps or build stage hit; min throws exactly those layers away. You can pass --cache-from more than once: import from this branch's cache first, then from main's, so a new branch starts warm.

On the default docker driver, these cache backends need the containerd image store, which is the default on fresh Docker Engine 29 and Docker Desktop installs. Otherwise create a docker-container builder. The official GitHub Actions setup step does that for you.

Measure, do not assume. Compare a cold build (--no-cache) with a warm one after a code-only change and after a lockfile change. If the warm build is not much faster, find the first miss with --progress=plain.

Match the pairs0/4 matched

Match each situation to the cache setup that fits.

Choose an item, then its match on the other side.

Multi-stage beyond the basics

One Dockerfile can serve every environment if you name the stages for what they are:

Dockerfile
# syntax=docker/dockerfile:1
FROM python:3.13-slim AS base
COPY --from=ghcr.io/astral-sh/uv:0.13.5 /uv /uvx /bin/
ENV UV_LINK_MODE=copy
WORKDIR /app
 
FROM base AS deps
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --locked --no-install-project --no-dev
 
FROM deps AS test
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --locked --no-install-project
COPY . .
RUN uv run pytest -q
 
FROM python:3.13-slim AS prod
RUN useradd --create-home --uid 10001 app
WORKDIR /app
COPY --link --from=deps /app/.venv /app/.venv
COPY --link app/ ./app/
ENV PATH="/app/.venv/bin:$PATH"
USER app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

CI runs docker build --target test . (a failing test fails the build), and the deploy job runs docker build --target prod, which skips the test stage entirely. Both reuse the same deps layers from the cache.

Two lines deserve a closer look:

  • COPY --from=<image> copies from any image, not only a stage. Pin the version (uv:0.13.5, or a digest), because a floating tag makes the build change under you.
  • COPY --link puts the copied files in a layer that does not depend on the layers below it. When the base image gets a security patch, BuildKit can reuse the existing --link layers and just restack them on the new base, instead of redoing every copy. The trade-off: a linked copy cannot see earlier files, so it cannot follow a symlink in the destination path. Check the docs before adding it everywhere.

Heredocs, build checks and ignore files

Heredocs make long RUN steps readable. Add set -e, because a heredoc runs as a script and, without it, only the last command's exit code counts:

RUN <<EOF
set -eux
apt-get update
apt-get install -y --no-install-recommends curl ca-certificates
rm -rf /var/lib/apt/lists/*
EOF

Build checks are a linter built into the frontend. Every build runs them and prints warnings; docker build --check . runs only the checks and exits non-zero on a violation, which makes a cheap CI step. Rules include JSONArgsRecommended (shell-form CMD, the PID 1 problem) and SecretsUsedInArgOrEnv (a secret-looking name in ARG or ENV). A # check=error=true directive at the top turns warnings into failures. Build checks need Dockerfile frontend 1.8 or newer, which the syntax line gives you.

Per-Dockerfile ignore files. When one repo holds several Dockerfiles, docker/api.Dockerfile.dockerignore next to docker/api.Dockerfile takes precedence over the root .dockerignore for that build.

Building several images with Bake

A monorepo with an API, a web app and a worker ends up with three long docker build commands in CI that drift apart. Bake (docker buildx bake) moves them into one file, builds the targets in parallel, and shares the work they have in common.

docker-bake.hcl
variable "TAG" {
  default = "dev"
}
 
group "default" {
  targets = ["api", "worker", "web"]
}
 
target "_python" {
  context = "./backend"
  args = { PYTHON_VERSION = "3.13" }
}
 
target "api" {
  inherits = ["_python"]
  target = "prod"
  tags = ["ghcr.io/acme/api:${TAG}"]
  cache-from = ["type=registry,ref=ghcr.io/acme/api:buildcache"]
  cache-to = ["type=registry,ref=ghcr.io/acme/api:buildcache,mode=max"]
}
 
target "worker" {
  inherits = ["_python"]
  target = "worker"
  tags = ["ghcr.io/acme/worker:${TAG}"]
}
 
target "web" {
  context = "./frontend"
  tags = ["ghcr.io/acme/web:${TAG}"]
}
docker buildx bake --printdocker buildx bake apiTAG=sha-7f3c2a1 docker buildx bake --push

--print shows the resolved configuration without building, which is the first thing to run when a Bake file misbehaves. Variables are overridden from environment variables of the same name. api and worker share the _python context and its deps stage, so BuildKit solves that stage once for both. Bake can also read a compose.yaml and turn each service's build: section into a target.

Failure modes seniors watch for

  • A cache mount hiding a broken lockfile. If a step installs from the cache without --locked (or npm ci), a stale cache can satisfy a dependency the lockfile no longer pins. Always install from the lockfile; the cache only saves downloads.
  • Registry cache growing without limit. A :buildcache ref per branch, each with mode=max, can quietly reach many gigabytes. Add a retention rule in the registry, and prefer one cache ref per image plus main.
  • mode=max making short builds slower. Exporting every layer of every stage takes time. For a two-minute build, measure whether the export costs more than it saves.
  • A floating COPY --from image. COPY --from=ghcr.io/astral-sh/uv:latest means two builds of the same commit can use different uv versions.
Put it in order5 steps

A Python service takes 6 minutes to build on hosted CI runners. Order these improvements from the one you should make first to the one you should make last.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
BuildKit
Docker's build engine and the default builder since Engine 23. It turns a Dockerfile into a graph and solves it with caching and parallelism.
Dockerfile frontend
The parser that turns a Dockerfile into BuildKit's graph. # syntax=docker/dockerfile:1 selects a current version.
cache mount
A directory kept by the builder across builds and mounted into one RUN step. Never in the image or the exported cache.
bind mount (build)
Files from the context or another stage mounted read-only into one RUN, without creating a layer.
remote cache
Layer cache exported to a registry, GitHub Actions or a directory, so a fresh builder can reuse earlier work.
mode=max
Cache export mode that keeps layers from every stage, not only those in the final image.
Bake
docker buildx bake: builds several targets defined in an HCL, JSON or Compose file, in parallel.