12.2.2.2 Node Lockfile Cache
A focused guide to Node Lockfile Cache, connecting core concepts with practical Docker and container operations.
Node lockfile cache refers to the Docker layer caching benefit gained by copying a Node.js project's package-lock.json (alongside package.json) before running the dependency install step, separate from the rest of the application's source code, allowing Docker to reuse this potentially slow step when only application code has changed.
Why Copying Order Determines Cache Effectiveness
Docker's layer caching invalidates a layer (and everything after it) only when that specific layer's inputs actually change — structuring the Dockerfile so the lockfile copy and install happen before the broader source code copy maximizes how often this caching can actually help.
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
As long as package.json and package-lock.json haven't changed, this npm ci layer remains cached even when the subsequent COPY . . (and any application code it brings in) changes.
Why Getting This Order Wrong Defeats the Caching Benefit
Copying the entire project before running the install step ties the install's cache validity to every file in the project, meaning any code change at all — even one entirely unrelated to dependencies — forces a full dependency reinstall.
COPY . .
RUN npm ci
This ordering means even a trivial, dependency-unrelated code change triggers a full reinstall on every subsequent build, losing the caching benefit entirely.
Measuring the Actual Time Savings This Provides
Comparing build times with and without this proper layer ordering demonstrates the caching benefit concretely.
time docker build -t myapp .
For a project with a substantial dependency tree, this difference in build time, specifically when only application code (not dependencies) changed, can be significant.
Applying the Same Pattern to Other Package Managers
This same layer-ordering principle applies equally to other Node.js package managers with their own lockfiles.
COPY yarn.lock package.json ./
RUN yarn install --frozen-lockfile
COPY . .
Why Node Lockfile Cache Matters
Deliberately structuring a Dockerfile to copy lockfiles before the broader application source is one of the most impactful, simple optimizations available for Node.js (and similar ecosystem) Docker builds, meaningfully speeding up the common case of rebuilding after only an application code change.