Skip to content
Latchkey

What Is Docker Layer Caching? Why the Second Build Is Fast

Docker layer caching reuses the result of an instruction when its inputs have not changed, so only the steps after a real change re-run.

The first time you build an image, every layer is created from scratch. The second time, Docker checks each instruction against its cache and reuses any layer whose inputs are identical. Understanding what invalidates the cache is the single biggest lever for fast Docker builds.

How the cache works

Docker walks the Dockerfile top to bottom. For each instruction it computes a cache key from the instruction and its inputs (for COPY, the file contents). If the key matches a cached layer, it reuses it. The first miss invalidates that layer and everything after it.

The cascade rule

Cache invalidation cascades. If line 5 changes, lines 5 through the end rebuild even if lines 6+ are untouched. That is why instruction order matters so much.

Order for cache hits

Put rarely changing steps first and frequently changing steps last. Copy your lockfile and install dependencies before copying source, so a code edit does not bust the dependency layer.

Cache in ephemeral CI

Fresh CI runners start with an empty local cache, so naive setups rebuild everything every time. Solutions include registry-based cache (--cache-from), BuildKit cache exports, or runners that persist the cache between jobs.

Caching on managed runners

Latchkey managed runners keep Docker layer caches warm across jobs, so the dependency and base layers are reused instead of rebuilt - turning multi-minute cold builds into seconds.

Key takeaways

  • A layer is reused when its instruction and inputs are unchanged.
  • Invalidation cascades - one changed line rebuilds everything after it.
  • Ephemeral CI needs an external or persistent cache to benefit.

Related guides

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