Faster Docker Builds with BuildKit Cache Mounts

A
Author
03 Jul, 2026 1 min read 959 views

Slow Docker builds usually re-download dependencies that haven't changed. BuildKit, the default builder in modern Docker, has features designed to stop that.

1. Order layers from least to most frequently changed

COPY package.json package-lock.json ./   # changes rarely
RUN npm ci                                # cached until the lockfile changes
COPY . .                                  # changes on every commit
RUN npm run build

2. Cache mounts for package managers

When dependencies do change, a cache mount keeps the package manager's download cache between builds, without storing it in the image:

# syntax=docker/dockerfile:1

# Node
RUN --mount=type=cache,target=/root/.npm npm ci

# Python with uv
RUN --mount=type=cache,target=/root/.cache/uv uv sync --frozen --no-dev

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

# Debian packages
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
    apt-get update && apt-get install -y --no-install-recommends libvips

3. Secret mounts instead of build args

RUN --mount=type=secret,id=npm_token \
    NPM_TOKEN=$(cat /run/secrets/npm_token) npm ci
docker build --secret id=npm_token,env=NPM_TOKEN .

Unlike ARG or ENV, the secret never ends up in an image layer or the build history.

4. Share the cache in CI

CI runners often start empty, so local caching doesn't help. Export the layer cache to a registry or the CI's cache store:

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:$GIT_SHA --push .

On GitHub Actions, docker/build-push-action supports cache-from: type=gha and cache-to: type=gha,mode=max to use the Actions cache.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.