Skip to main content
Efficient use of Docker’s build cache can dramatically speed up your image builds. Docker creates a cache layer for each instruction in your Dockerfile. When you rebuild the image, Docker reuses layers whose instructions and contexts haven’t changed, avoiding redundant work.

How Docker’s Build Cache Works

  • Each RUN, COPY, or ADD instruction produces a layer.
  • After a successful build, layers are stored in the local cache.
  • On subsequent builds, Docker compares:
    1. The instruction itself.
    2. Any files referenced by COPY/ADD.
  • If both match the cached layer, Docker reuses it.
  • Any change invalidates that layer and all subsequent layers, triggering a rebuild from that point.

Cache Invalidation Example

Changing the pip install command:
Invalidates the pip3 install layer and everything that follows—earlier layers remain cached. Similarly, updating app.py in:
busts the cache from that layer onward.

Cache Busting with Combined Instructions

Separating apt-get update and apt-get install can lead to stale package lists:
Stale package lists may cause installation of outdated or missing packages.
Instead, combine them:
  • Forces an update immediately before installation.
  • Lists packages alphabetically and on separate lines for readability.
Always include && rm -rf /var/lib/apt/lists/* if you want to reduce image size.

Version Pinning

Pinning package versions ensures consistent builds across environments:

Optimizing Instruction Order

Place instructions that change least frequently at the top of your Dockerfile. This maximizes cache reuse.

Example: Optimal Order

By contrast, placing COPY app.py first forces Docker to rerun all subsequent layers on every code update, significantly slowing builds.

Further Reading

Watch Video