Docker 镜像以层的方式构建——每个 Dockerfile 指令创建一个层,Docker 缓存这些层以加速重新构建。理解层和缓存是编写高效 Dockerfile 的关键,这样的 Dockerfile 构建速度快且生成的镜像较小。
层——每个指令添加一个层
Each Dockerfile instruction (FROM, RUN, COPY, etc.) creates a read-only LAYER:
→ layers stack to form the image; layers are CACHED and SHARED between images
→ if a layer is unchanged, Docker REUSES the cached layer (skips rebuilding it)
→ Layer caching makes rebuilds fast — only changed layers (and those AFTER) rebuild.
缓存规则(顺序很重要)
Docker caches layers IN ORDER. When an instruction's input changes, that layer AND
ALL layers AFTER IT are rebuilt (cache invalidated from that point down).
→ Put STABLE things EARLY and FREQUENTLY-CHANGING things LATE in the Dockerfile.
