Docker Cache Optimization: Speed Up Builds
In this article
Docker's layer caching can dramatically speed up image builds by reusing unchanged layers from previous builds. Instead of re-running every instruction, Docker only rebuilds layers that changed and everything after them. This guide shows you how to structure your Dockerfile and workflow to maximize cache hits, reducing build times from minutes to seconds.
What You'll Need
- Docker installed (version 19.03 or later recommended)
- A Dockerfile for an existing project
- Basic familiarity with the command line and Docker commands
Step-by-Step
- Order instructions from least to most frequently changing. Place commands that rarely change (like installing OS packages) at the top of your Dockerfile, and frequently changing code (like copying source files) near the bottom. This ensures the stable layers are cached and reused.
- Copy dependency files before source code. If you use a package manager (npm, pip, apt, etc.), copy only the manifest files (e.g.,
package.json,requirements.txt) first, run the install command, then copy the rest of the source. This way, dependency installation is cached unless the manifest changes. - Combine RUN commands that modify the same filesystem area. Each
RUNcreates a new layer. Combining related commands with&&reduces the number of layers and avoids invalidating the cache when only one command's output changes. - Use
--cache-fromfor CI or multi-stage builds. When building in a CI pipeline, you can pull a previously built image and use it as a cache source:docker build --cache-from=myimage:latest .This works especially well with multi-stage builds where you can reference an earlier stage as a cache source. - Leverage BuildKit for better cache management. Enable BuildKit by setting
DOCKER_BUILDKIT=1or using Docker's default (if your version supports it). BuildKit offers features like--mount=type=cachefor package manager caches (e.g.,RUN --mount=type=cache,target=/var/cache/apt) and better cache invalidation. - Use
.dockerignoreto exclude unnecessary files. Create a.dockerignorefile in the build context to exclude logs, temporary files, and large directories (likenode_modulesor.git). This reduces the context size and prevents changes in those files from invalidating the cache. - Pin base image versions. Use specific tags (e.g.,
python:3.12-slim) instead oflatestto ensure the base layer stays consistent. If the base image tag changes, the cache is invalidated. - Monitor cache usage with
docker history. Rundocker history myimageto see the layers and their sizes. This helps you identify which layers are large and whether they are being reused.
Common Mistakes
- Copying everything at the top. If you copy the entire source before running installs, any source change invalidates the dependency layer.
- Using
COPY . .too early. This copies all files, including those that change often, and forces a rebuild of every subsequent layer. - Not using
.dockerignore. Sending a large build context slows down the build and can cause unnecessary cache misses. - Running
apt-get upgradeor similar. These commands often produce different output each time, breaking cache. - Ignoring cache invalidation from environment variables. Changing an
ENVvalue invalidates all subsequent layers.
Tips
- Use multi-stage builds. Separate build tools from runtime dependencies. The final stage only copies artifacts from the build stage, keeping the image small and cache-friendly.
- Leverage BuildKit's inline cache. When pushing to a registry, use
--cache-fromand--cache-toto export cache metadata:docker build --cache-from=myimage --cache-to=type=inline -t myimage .This allows CI to use the cache from a previously pushed image. - Keep the build context minimal. Use
.dockerignoreto exclude everything not needed for the build. - Use specific base images. Alpine or slim variants are smaller and often have fewer updates, making cache more stable.
Troubleshooting
Cache is not being used at all. Check if you are building with --no-cache (remove it). Also verify that the build context hasn't changed unexpectedly (e.g., a file timestamp changed). If using CI, ensure the cache source image is pulled.
Cache is invalidated after a small change. Review the order of instructions. A change in a COPY or ENV will invalidate all subsequent layers. Move frequently changing steps to the end.
Build context is large and slow. Add a .dockerignore file. Run docker system df to see if you have unused images or build cache taking up space.
BuildKit cache mount not working. Ensure you have # syntax=docker/dockerfile:1.2 or later at the top of your Dockerfile, and that BuildKit is enabled.
Frequently Asked Questions
Does Docker cache automatically?
Yes, Docker caches layers by default. If a layer's instruction and its context (files, environment) haven't changed, it is reused from the local cache.
How can I see which layers are cached?
During a build, Docker prints Using cache for cached layers. You can also run docker history on an image to see layer details.
Why does my cache get invalidated when I change a comment in a file?
Because Docker compares the checksum of the files copied. Any change, even whitespace, invalidates the COPY layer and everything after it.
Can I use cache from a previous build in CI?
Yes. Use --cache-from to reference a previously pushed image. For example: docker build --cache-from=myapp:latest -t myapp:latest .
Does the order of layers matter?
Absolutely. The more stable layers at the top, the more cache hits you get. Place frequently changing steps (like source code copy) near the end.
Is BuildKit better for caching?
Yes, BuildKit offers more advanced caching features like cache mounts and inline cache, which can significantly improve build performance in CI.