intermediate

Layers

Use layer caching deliberately so dependency, source, and build-output changes invalidate only the necessary image steps.

Image layers are cached filesystem deltas. Efficient Node.js images place slow-changing dependency inputs before frequently changing source so rebuilds reuse dependency layers without hiding correctness inputs.

					# Good: lockfile change invalidates only install layer
COPY package.json package-lock.json ./
RUN npm ci
COPY src ./src
RUN npm run build

# Bad: any source edit invalidates install
COPY . .
RUN npm ci && npm run build
				

Cache keys in CI should include lockfile hash, base image digest, and platform (`linux/amd64` vs `arm64`) when native modules matter.

On interviews: cache invalidation, why lockfile changes must bust installs, and how layer order affects CI and local feedback.

Common pitfalls: over-optimizing cache preserves stale generated artifacts; giant `RUN` chains make debugging harder.

The trade-off is faster rebuilds versus the risk of serving stale layers when inputs are incomplete.

Checklist:

  • Cache dependencies by manifest and lockfile.
  • Invalidate on source or config changes that affect output.
  • Keep layers understandable and separable.
  • Include platform in cache keys when native deps differ.