Docker Build Cache Explained: How to Cut Build Times

https://hackernoon.imgix.net/images/GebCiMsD9rWTnXjyB0zwrW2yZxM2-wd83fpj.webp

Build that takes eight minutes when it should take forty seconds is almost always a cache ordering problem. The dependency install runs every time because something above it changed, and the thing above it changes on every commit.

Understanding the cache key makes this predictable rather than mysterious.

How the key is computed

Each instruction produces a layer, and each layer's cache key includes the key of the layer before it. Changing layer three and layers four onward are invalidated regardless of whether their own content changed. The chain is the whole mechanism.

What goes into the key depends on the instruction:

Key includes

RUN

The literal command string, not its effects

COPY / ADD

Contents and metadata of the files copied

ENV, ARG

The value, and it invalidates everything after

FROM

The resolved image digest

The RUN case is the one that surprises people. RUN apt-get update is cached...

Copyright of this story solely belongs to hackernoon.com. To see the full text click HERE