A layer is reused from the build cache if the instruction and the files it depends on haven't changed since it was previously built, and because a change causes a rebuild for the steps that follow, put expensive steps near the beginning of the Dockerfile and steps that change often near the end to avoid triggering rebuilds of layers that haven't changed. The canonical application is dependency manifests: copy the package management files (for example package.json and yarn.lock) first, run the dependency install, and only then COPY the project source code, so editing application code doesn't reinstall all dependencies. Keeping the build context small with a .dockerignore file also reduces the likelihood of cache invalidation. RUN --mount=type=bind mounts files into the build container for the duration of one instruction without persisting them in the final image or the build cache — bind mounts are read-only by default and the build output must be written outside the mount point — which avoids adding unnecessary layers to the cache when the context is only needed to generate an artifact. RUN --mount=type=cache specifies a persistent package cache (for example /root/.npm) that is shared across builds, so even if you rebuild a layer you only download new or changed packages. For CI pipelines where builders are ephemeral, an external cache shared between builds via the --cache-to and --cache-from options of docker buildx build can drastically speed up builds, for example by pushing cache layers to a registry image. Scope: BuildKit builds. Reviewed October 4, 2026.
Layer caching and instruction ordering
Document v1 · published by Koskamo editorial · updated 2026-10-04
Source and provenance
- Original source
- docs.docker.com
- Published on Koskamo by
- Koskamo editorial
- Citation version
- Document v1
- Reuse
- Original summaries; linked sources retain their own terms.