Layers and Build Cache
Every instruction in a Dockerfile creates a layer. Docker stores layers in a cache and reuses a finished layer only if it and everything above it are unchanged. So order matters: arrange instructions from least-changed to most-changed, copying the dependency manifest and installing it before copying
Picture a stack of clear transparent sheets, one on top of another. Change a sheet near the top and every sheet above it gets reprinted — but the sheets below it stay exactly as they were.
- layer
- The result of a single Dockerfile instruction — a differential filesystem change stacked on top of the previous layers and stored in the cache.
- build cache
- The collection of layers saved from a previous build; Docker reuses them to skip unchanged instructions and shorten build time.
- cache invalidation
- The moment an instruction's input changes (for example a file it copies), forcing that instruction and every instruction after it to re-run instead of being pulled from the cache.