.dockerignore file fixes the first and keeps secrets and junk out of images. Ordering the Dockerfile from least to most frequently changing fixes the second. BuildKit cache mounts keep package manager caches across builds, and exporting the cache to a registry or your CI provider makes CI builds as fast as local ones.
A developer changes one line in a controller. docker build starts by printing “Sending build context to Docker daemon 1.9GB”, then reinstalls 900 npm packages, then finally copies the one changed file. Four minutes for a one-line change, every time. Meanwhile, the image quietly includes the developer’s .env file, because COPY . . copied everything in the directory.
The build context and .dockerignore
The path at the end of docker build -t app . is the build context. The builder can only COPY files from it, and the client sends it to the builder before the build starts. BuildKit, the default builder since Docker Engine 23.0, transfers only the files a build actually references, which helps, but COPY . . still references everything.
A .dockerignore file in the root of the context excludes paths, using patterns similar to .gitignore:
# Version control and editor files
.git
.gitignore
.vscode
.idea
# Dependencies and build output: rebuilt inside the image
node_modules
dist
build
__pycache__
*.pyc
.venv
# Local configuration and secrets
.env
.env.*
!.env.example
*.pem
*.key
# Logs, tests output, OS junk
*.log
coverage
.DS_Store
# Docker files themselves
Dockerfile*
docker-compose*.yml
Patterns match from the context root; ** matches any number of directories, and a line starting with ! re-includes something an earlier pattern excluded, as with .env.example above. Unlike .gitignore, a pattern like node_modules only matches at the root; use **/node_modules for nested ones in a monorepo.
Excluding node_modules matters twice over: it shrinks the context, and it stops a node_modules folder built on your Mac, with native modules compiled for macOS, from overwriting the Linux one installed inside the image.
How the layer cache decides
For every instruction, the builder computes a cache key and reuses the layer from a previous build if the key matches:
- The parent layer must be the same. Once one instruction misses the cache, every instruction after it is rebuilt.
RUNinstructions match on the exact command text. The builder does not know thatapt-get install curlwould produce a different result today than last month.COPYandADDmatch on a checksum of the copied files’ contents and metadata. Changing any copied file invalidates the step.ARGvalues used by a step are part of its key.
The first rule is the one to design around: a cache miss cascades down the file.
Order instructions by how often they change
# SLOW: any source change invalidates npm ci
FROM node:18-bullseye-slim
WORKDIR /app
COPY . .
RUN npm ci
CMD ["node", "server.js"]
# FAST: npm ci is cached until package files change
FROM node:18-bullseye-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
CMD ["node", "server.js"]
The same pattern applies everywhere: copy requirements.txt before the Python source, go.mod and go.sum before the Go source, pom.xml before src. Put system packages first, language dependencies next, application code last, and metadata like CMD and LABEL at the end.
The stale apt-get update trap
# WRONG: the update layer is cached forever; the install later uses stale package lists
RUN apt-get update
RUN apt-get install -y curl
# RIGHT: update and install together
RUN apt-get update && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
Because RUN apt-get update never changes text, its cached layer can be months old. When you later add a package to the separate install line, apt tries to download versions that no longer exist on the mirrors and the build fails.
BuildKit cache mounts
Layer caching is all-or-nothing: if package-lock.json changes by one dependency, npm ci reruns and downloads everything again. A cache mount gives a RUN step a persistent directory that survives between builds but is never part of the image:
# syntax=docker/dockerfile:1
RUN --mount=type=cache,target=/root/.npm \
npm ci
RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r requirements.txt
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
go build -o /out/api ./cmd/api
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 git
Now a changed lockfile still reruns the step, but the package manager finds most packages in its local cache. Go’s build cache also makes recompiles incremental. The # syntax line ensures the builder supports the mount syntax.
Caching in CI
CI runners are usually fresh machines with an empty cache, so every pipeline builds from scratch. Buildx, the BuildKit-based build command, can export the cache somewhere persistent and import it next time:
# Store cache in the registry next to the image
docker buildx build \
--cache-from type=registry,ref=ghcr.io/acme/billing-api:buildcache \
--cache-to type=registry,ref=ghcr.io/acme/billing-api:buildcache,mode=max \
-t ghcr.io/acme/billing-api:${GIT_SHA} --push .
# On GitHub Actions, use the Actions cache backend
docker buildx build --cache-from type=gha --cache-to type=gha,mode=max ...
mode=max exports layers from every stage of a multi-stage build, not just the final one, so the dependency stages are cached too. The Docker CI/CD guide shows this inside a full GitHub Actions workflow.
When to bypass the cache
docker build --pullchecks for a newer version of the base image instead of using the local one. Use it in CI so security patches in the base image are picked up.docker build --no-cacherebuilds every step. Use it occasionally, for example in a scheduled weekly build, soRUNsteps that install packages get fresh versions.docker builder pruneclears the local build cache when it grows large;docker system dfshows how much space it uses.
Frequently Asked Questions
What does .dockerignore do?
It excludes files and directories from the build context, so they are not sent to the builder and cannot be copied into the image. Use it to skip .git, node_modules, build output, logs and local secrets such as .env files.
Why does Docker reinstall my dependencies on every build?
Usually because the Dockerfile copies all source code before installing dependencies, so any code change invalidates the cache for the install step. Copy only the dependency manifests, install, and then copy the rest of the code.
What is a BuildKit cache mount?
RUN –mount=type=cache gives a build step a persistent directory, such as a package manager’s download cache, that survives between builds but is not stored in the image. Dependency installs stay fast even when the lockfile changes.
How do I cache Docker builds in CI?
Use docker buildx with –cache-to and –cache-from, pointing at a registry cache image or a CI-specific backend such as type=gha on GitHub Actions. Use mode=max to cache intermediate stages of multi-stage builds.
Small context, stable layers, persistent caches
Fast Docker builds come from three habits: send the builder only what it needs, order the Dockerfile so expensive steps depend on files that rarely change, and give package managers a cache that outlives each build. Combined with the patterns from multi-stage builds, a change to one line of code should rebuild in seconds, not minutes. The official documentation is worth keeping open: the Docker build cache documentation and the .dockerignore reference. Related reading on this site: Dockerfile fundamentals.
Originally posted on 25 April 2023 and post last modified on 25 April 2023