How does Docker layer caching work?medium

Type
applied
Topic
build-optimization
Frequency
common
Tags
build, optimization
Answer

Docker caches each instruction's result. If an instruction and its inputs have not changed since the last build, Docker reuses the cached layer - skipping re-execution.

Explanation

Cache is invalidated from the changed instruction downward. Best practice: copy dependency files first, run install, then copy application code. Example for Python: COPY requirements.txt . -> RUN pip install -> COPY . . . This way, changing source code only invalidates the last COPY, not the slow pip install. A single changed file early in the Dockerfile invalidates all subsequent layers.

Follow-upHow do you force a full rebuild ignoring cache?