19 Nov, 2026Aishwarya Palta
Dockerfile Ordering: Keep Dependencies Cached
Fix Dockerfile ordering and use .dockerignore to avoid reinstalling unchanged dependencies. Follow a Node.js example and verify cache reuse after edits.
Dockerfile Ordering: Keep Dependencies Cached
Dockerfile ordering determines whether a source edit also triggers dependency installation. Copy dependency manifests first, install packages, then copy application code; use .dockerignore to exclude files the build does not need.
Our developer view: prevent unnecessary work before adding more compute. This makes a small application change easier to build and its timing easier to explain.
Why does changing one file reinstall everything?
When COPY . . appears before installation, changes to copied files can invalidate that layer and the steps after it. Docker documents the relevant cache invalidation rules.
For a single npm application with committed `package.json`, `package-lock.json` and a working `build` script, use this build-stage example:
```dockerfile
FROM node:24-bookworm-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
```
Source changes now occur after dependency installation. Lockfile changes still invalidate installation, which is the behavior we want. For workspaces or install scripts that require source files, copy those required inputs before npm ci too.
What belongs in .dockerignore?
Exclude local dependencies, generated output and files unrelated to building. For this example, start with:
```text
node_modules
.git
dist
coverage
*.log
```Check that these exclusions match your application. A build that consumes prebuilt `dist` files must receive them. Docker’s cache optimization guide explains context reduction and layer ordering.
How can you verify the improvement?
- Build with docker build --progress=plain . to populate the cache.
- Change application source without changing dependency files, then repeat.
- Look for CACHED on the dependency step and compare total duration.
- Change a dependency through npm, then confirm installation executes again.
A correctly ordered Dockerfile still needs access to its previous cache. Fresh CI builders need an appropriate persistent or external cache; see Monk CI’s Docker cache.
Keep this experiment separate from a runner-size comparison. For the broader workflow, follow the Docker migration guide.
Takeaway: verify which instruction reruns after each kind of change. Cache hits matter when they eliminate work your build would otherwise repeat.