Skip to content
Latchkey

Building Images Fast with BuildKit and buildx

BuildKit parallelizes independent build steps and adds cache mounts -- features the legacy builder simply does not have.

BuildKit is the modern Docker build engine, and buildx is the CLI that drives it. Together they make builds faster and give you the caching controls you need in CI. This lesson covers the features that matter most for pipelines.

What BuildKit adds

  • Parallelism: independent stages and instructions build concurrently.
  • Cache mounts: persist package-manager caches across builds with RUN --mount=type=cache.
  • Build secrets: pass credentials at build time without baking them into a layer.
  • Remote cache: import and export the layer cache to a registry or CI cache.

Using a cache mount

A cache mount keeps a directory (like a package cache) between builds without putting it in a layer. This speeds up dependency installs dramatically.

Dockerfile
# syntax=docker/dockerfile:1
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm \
    npm ci

Driving builds with buildx

buildx exposes BuildKit features like inline cache export and multi-platform output. Create a builder once, then build with cache flags.

Terminal
docker buildx create --use --name ci-builder
docker buildx build \
  --cache-from type=registry,ref=ghcr.io/acme/myapp:buildcache \
  --cache-to type=registry,ref=ghcr.io/acme/myapp:buildcache,mode=max \
  -t ghcr.io/acme/myapp:ci --push .

When the speedup shows up

BuildKit helps most when your build has independent stages or expensive dependency installs. Combined with a remote cache, a CI build can skip nearly all work when only application code changes.

Key takeaways

  • BuildKit parallelizes builds and adds cache mounts, build secrets, and remote caching.
  • RUN --mount=type=cache persists package caches across builds without bloating layers.
  • buildx exposes registry-backed cache import/export for fast CI builds.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →