You push a one-line fix. The Docker build takes eight minutes. You do this twelve times a day. Your team has nine people. Nobody has done the math on how much time this wastes, and honestly, nobody should, because the number would be depressing.

Most slow Docker builds are slow because the Dockerfile was written once, fast, and never revisited. The tools to fix this have shipped with Docker for years. Almost nobody uses them properly.

This guide covers everything from layer caching basics to Buildx cache backends. It is long because the topic has a lot of moving parts, not because I'm padding it.


Part 1: Why your builds are slow

The layer cache and its domino problem

Every Dockerfile instruction (FROM, COPY, RUN, etc.) produces a layer. Docker stores these layers and reuses them when nothing has changed. This is the layer cache.

The thing that trips people up: the cache is sequential. If any layer gets invalidated, every layer after it rebuilds from scratch, even if those later layers haven't changed. One dirty layer in the middle knocks everything downstream out.

This explains why most slow Dockerfiles are slow. Here's a typical one:

FROM node:18-alpine
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]

COPY . . sits above RUN npm install. Every time any file in your project changes (a component, a README, a test), Docker sees the COPY layer as dirty and re-runs npm install from scratch. Your dependencies haven't changed, but Docker doesn't know that.

Build context bloat

When you run docker build, Docker sends your entire project directory to the builder daemon. If you're not excluding node_modules, .git, test artifacts, and screenshots, you might be shipping hundreds of megabytes of irrelevant data every build. One team I know of measured their context at 700 MB before adding a .dockerignore, and 37 MB after.

The base image tax

Using ubuntu:latest or a full python:3.11 image when you only need a fraction of what they ship is just waste. You're pulling hundreds of megabytes of packages you'll never call, and on CI runners that download fresh every time, it adds up fast.


Part 2: The fundamentals (get these right first)

These are high-leverage changes that don't require special tooling. They work with the default Docker builder.

2.1 Reorder your Dockerfile: dependencies before source code

The single most impactful change you can make is separating dependency installation from source code copying:

FROM node:18-alpine
WORKDIR /app

# 1. Copy ONLY dependency manifests
COPY package.json package-lock.json ./

# 2. Install dependencies (cached unless package files change)
RUN npm ci

# 3. Copy source code LAST (only this layer rebuilds on code changes)
COPY . .

RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]

Same idea in every language:

# Python
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .

# Go
COPY go.mod go.sum ./
RUN go mod download
COPY . .

# Java/Maven
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src/ ./src/

This alone can cut build times in half because Docker only reinstalls packages when the dependency manifest actually changes.

2.2 Add a proper .dockerignore

A .dockerignore keeps junk out of the build context. Fewer files means fewer things that can break your cache and less data shipped to the daemon:

.git
node_modules
dist
*.md
*.log
.env*
docker-compose*.yml
Dockerfile*
.github
tests
coverage
__pycache__
.next

2.3 Use slim base images

Pick the leanest image that can still run your application:

# ~900 MB, you almost certainly don't need this
FROM ubuntu:latest

# ~150 MB, reasonable
FROM python:3.11-slim

# ~50 MB, good default for Node
FROM node:20-alpine

2.4 Use multi-stage builds

Multi-stage builds let you compile in a full development image, then copy only the finished artifacts into a slim runtime image. Build tools, dev dependencies, and intermediate files stay out of the final image:

# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

# Stage 2: Production (only the output)
FROM node:20-alpine AS production
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY package.json ./
EXPOSE 3000
CMD ["node", "dist/index.js"]

Smaller image, smaller attack surface, and BuildKit can parallelize independent stages.


Part 3: BuildKit, Docker's modern build engine

BuildKit is Docker's newer build engine, introduced in 2018 and the default since Docker 23.0. If you're on an older version, enable it explicitly:

DOCKER_BUILDKIT=1 docker build -t myapp .

Or use docker buildx build, which always uses BuildKit under the hood.

BuildKit adds parallel stage execution, advanced caching, mount support during builds, and pluggable cache backends.

3.1 Parallel stage execution

The legacy builder runs multi-stage builds sequentially. BuildKit analyzes the dependency graph and runs independent stages in parallel. If your builder, tester, and linter stages all depend only on a shared deps stage, they run simultaneously:

FROM node:20 AS base
WORKDIR /app
COPY package*.json ./
RUN npm ci

FROM base AS builder
COPY . .
RUN npm run build

FROM base AS tester
COPY . .
RUN npm test

FROM base AS linter
COPY . .
RUN npm run lint

FROM node:20-slim AS production
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/server.js"]

BuildKit runs builder, tester, and linter concurrently because they all branch from base.

3.2 Cache mounts (--mount=type=cache)

This is the most underused BuildKit feature. Cache mounts persist a directory across builds without including it in the final image layer. They're made for package manager caches.

The pattern is always the same: mount the cache directory your package manager uses.

# syntax=docker/dockerfile:1

# Node.js
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm \
    npm ci
COPY . .

# Python
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install -r requirements.txt
COPY . .

# Go
FROM golang:1.22
WORKDIR /app
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    go build -o /app/hello

# APT (note: sharing=locked)
FROM ubuntu:22.04
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 curl git

# Maven
FROM maven:3.9-eclipse-temurin-17 AS build
WORKDIR /app
COPY pom.xml .
RUN --mount=type=cache,target=/root/.m2 \
    mvn dependency:go-offline

How it works: when the RUN instruction executes, BuildKit mounts the specified directory into the container. After the command finishes, the cache directory detaches. Its contents persist in BuildKit's internal storage but never get written into an image layer. On the next build, even if the layer itself is invalidated (say you added a new dependency), the package manager finds its cache already populated and only downloads what's new.

Options worth knowing:

  • target: the directory to mount inside the container (required)

  • id: a unique identifier for the cache, defaults to the target path. Use different IDs to isolate caches between stages or projects: --mount=type=cache,id=pip-prod,target=/root/.cache/pip

  • sharing: concurrency mode. shared (default) allows parallel reads/writes. Use locked for package managers like APT that can corrupt under concurrent access

One caveat: cache mounts are local to the build machine. On ephemeral CI runners, the cache starts empty every time unless you export it (covered in Part 4).

3.3 Bind mounts (--mount=type=bind)

Bind mounts let you temporarily mount files from the build context into a RUN instruction without adding them as a layer. Useful when you need source files only to generate an artifact:

RUN --mount=type=bind,source=./package.json,target=package.json \
    --mount=type=bind,source=./package-lock.json,target=package-lock.json \
    --mount=type=cache,target=/root/.npm \
    npm ci

The package.json and package-lock.json are available during npm ci but aren't permanently copied into the image. Changes to these files don't create a new layer in themselves; only the installed node_modules matters.


Part 4: Buildx cache backends (sharing cache across machines)

Everything in Parts 2 and 3 works well on a single machine where BuildKit's internal cache persists. But CI/CD pipelines often run on ephemeral runners where every job starts fresh. This is where Buildx cache backends come in.

docker buildx build supports --cache-from (import) and --cache-to (export) flags that let you store build cache externally.

4.1 Cache backend types

BuildKit supports several cache storage backends:

Inline cache. Embeds cache metadata into the image you push. Simplest setup, but only caches the final stage of a multi-stage build (min mode only), which makes it inefficient for complex Dockerfiles.

docker buildx build --push -t user/app:latest \
    --cache-from type=inline \
    --cache-to type=inline .

Registry cache. Pushes cache to a dedicated image in your container registry, separate from the main image. Supports max mode (caches all intermediate stages), which is far more effective for multi-stage builds.

docker buildx build --push -t user/app:latest \
    --cache-from type=registry,ref=user/app:buildcache \
    --cache-to type=registry,ref=user/app:buildcache,mode=max .

Local cache. Writes cache to a local filesystem directory. Useful when you have persistent storage on your CI runner.

docker buildx build -t myapp:latest \
    --cache-from type=local,src=/tmp/buildx-cache \
    --cache-to type=local,dest=/tmp/buildx-cache,mode=max .

GitHub Actions cache (GHA). Stores cache in GitHub's native cache service. Built for GitHub Actions workflows.

docker buildx build --push -t user/app:latest \
    --cache-from type=gha \
    --cache-to type=gha,mode=max .

4.2 min vs max mode

This distinction matters:

  • mode=min (default): only caches layers that appear in the final image. Smaller cache, faster export/import, but misses intermediate build stages.

  • mode=max: caches all layers, including intermediate stages. Larger cache, but much higher cache hit rates for multi-stage builds.

For most CI/CD setups, mode=max is worth the extra storage because your dependency installation stages get cache hits even when later stages change.

4.3 Multi-source cache imports

You can import cache from multiple locations, which is useful for branch-based caching:

docker buildx build --push -t registry/app:$BRANCH \
    --cache-from type=registry,ref=registry/app:cache-$BRANCH \
    --cache-from type=registry,ref=registry/app:cache-main \
    --cache-to type=registry,ref=registry/app:cache-$BRANCH,mode=max .

Feature branches try their own cache first, then fall back to main's cache.

4.4 GitHub Actions: full example

Here's a GitHub Actions workflow that combines everything:

name: Build and Push
on: push

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

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

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

A note about cache mounts in CI: --cache-from and --cache-to only persist the layer cache, not cache mount contents. Cache mounts (--mount=type=cache) are stored locally in BuildKit's internal storage and are not exported by default. To persist cache mounts across CI runs, you can use the reproducible-containers/buildkit-cache-dance GitHub Action, which extracts and re-injects cache mount data between builds.


Part 5: Avoiding sneaky cache busters

Even with good Dockerfile ordering and external cache, certain patterns silently invalidate your cache every build.

Dynamic build arguments. CI systems often inject variables like BUILD_NUMBER or GIT_SHA as build args. If those ARG declarations sit near the top of your Dockerfile, the cache breaks on every run. Move them to the very end:

# Bad: kills cache from here down on every build
ARG GIT_SHA
RUN echo $GIT_SHA > /app/version.txt
COPY . .
RUN npm run build

# Good: put it at the end
COPY . .
RUN npm run build
ARG GIT_SHA
RUN echo $GIT_SHA > /app/version.txt

Unpinned versions. RUN curl -sSL https://example.com/install.sh | sh or apt-get install -y some-package without version pinning fetches whatever's current, which can change between builds. Pin your versions.

Timestamp-dependent commands. Anything that generates output based on the current time (date, build timestamps in files) will differ between builds.


Part 6: Putting it all together

Here's an optimized Dockerfile for a Node.js application that applies every technique from this article:

# syntax=docker/dockerfile:1

# Stage 1: Install dependencies
FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
    npm ci

# Stage 2: Build the application
FROM deps AS builder
COPY . .
RUN npm run build

# Stage 3: Production image
FROM node:20-alpine AS production
WORKDIR /app
ENV NODE_ENV=production

# Copy only what's needed
COPY --from=deps /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY package.json ./

EXPOSE 3000
CMD ["node", "dist/index.js"]

Paired with this .dockerignore:

.git
node_modules
dist
*.md
*.log
.env*
Dockerfile*
docker-compose*
.github
tests
coverage

And built with:

docker buildx build \
    --cache-from type=registry,ref=myrepo/app:buildcache \
    --cache-to type=registry,ref=myrepo/app:buildcache,mode=max \
    -t myrepo/app:latest \
    --push .


Cache mount targets by ecosystem

Package Manager

Cache Mount Target

npm

/root/.npm

yarn

/usr/local/share/.cache/yarn

pip

/root/.cache/pip

Go modules

/go/pkg/mod

Go build cache

/root/.cache/go-build

Maven

/root/.m2/repository

Gradle

/root/.gradle

APT

/var/cache/apt + /var/lib/apt (use sharing=locked)

apk (Alpine)

/var/cache/apk

Cargo (Rust)

/usr/local/cargo/registry


Checklist

  1. Reorder your Dockerfile: dependency files first, install, then source code

  2. Add .dockerignore: exclude .git, node_modules, test artifacts, build output

  3. Use slim base images: Alpine or -slim variants

  4. Use multi-stage builds: separate build tools from the production runtime

  5. Enable BuildKit: DOCKER_BUILDKIT=1 or use docker buildx build

  6. Add cache mounts: RUN --mount=type=cache,target=... for every package manager

  7. Export cache in CI: --cache-from and --cache-to with mode=max

  8. Kill cache busters: move dynamic ARGs to the end, pin versions, avoid timestamps

  9. Use registry or GHA cache backends so ephemeral CI runners aren't rebuilding from zero

  10. Prune periodically: docker buildx prune --filter "until=48h" to reclaim disk space


The difference between a naive Dockerfile and an optimized one isn't 10%. It's often 10x to 200x. Eight minutes down to 24 seconds. Fifteen minutes down to under a minute. The tools are there, they've been there for years, and there's no good reason not to use them.