CodePark/ questions / Layers & build cache
START PRACTICINGPRACTICE
Backend question · Docker › Layers & build cache

How does the Docker build cache work, and what invalidates it?

Docker reuses a cached step when the instruction and its inputs have not changed. Once one step changes, every step after it is rebuilt.

Instructions that change the filesystem each produce a layer: a saved snapshot of the file changes from that step. These are mainly RUN, COPY and ADD. When you rebuild, the builder checks each instruction in order. If the instruction and its inputs are unchanged, it reuses the cached result.

What counts as "changed" depends on the instruction:

  • For RUN, the cache key is the command text. So RUN apt-get update is reused even if the remote package lists have changed.
  • For COPY and ADD, the builder checks the files being copied. Changing any copied file invalidates that step.

When one step misses the cache, every later step is rebuilt too. This happens because each layer builds on the one before it. So put steps that rarely change first. Put steps that change often last, like copying your source code.

  • RUN, COPY and ADD create filesystem layers.
  • RUN is cached by its command text.
  • COPY and ADD are invalidated when the copied files change.
  • A cache miss rebuilds every later step.
  • Order steps from least often changed to most often changed.