Keep Docker dependency installs cached when application code changes
Copy the dependency manifests before the application files. Docker can then reuse the install layer after a source-only edit when its inputs and prior layers still match.
Give the install step a smaller set of inputs
In a simple npm app with a committed package-lock.json, first copy package.json and package-lock.json. Next run npm ci. Copy the application source after that step. This ordering lets a source edit invalidate the later COPY while keeping the install step eligible for reuse.
For a monorepo or a build using local dependencies, include the workspace manifests and other files needed by the package manager before installing. Match the copied inputs to what the installer actually reads.
Check the two rebuild paths
Build twice with the same builder and plain progress output, changing only one application file before the second run. The dependency step can display CACHED while the source-copy step runs again. Then change a dependency and regenerate the lockfile. The manifest-copy step and the install step should run again.
A fresh builder without the old cache will have to run the install initially. A source-only edit and a dependency edit are a useful pair of tests because they check cache reuse and invalidation independently. This example follows Docker’s documented cache rules.