Build images
Use layer caching deliberately
Order Dockerfile instructions so dependency installation is reused until its real inputs change.
8 minute lesson
Docker can reuse an unchanged build step and the layers before it. A change invalidates that step and every step that follows.
Copy dependency manifests and install dependencies before copying frequently changing application code. A source edit then keeps the expensive dependency layer cached, while a package change correctly rebuilds it.
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY server.js ./
CMD ["node", "server.js"]
Caching must remain correct before it becomes fast. Every dependency installation step needs all of its real inputs, including the lockfile. If a script, configuration file, or package-manager setting affects installation, copy it before the install step too. Otherwise Docker may reuse a layer whose inputs were incomplete.
Use --no-cache to diagnose stale build layers, not as a normal workflow. It forces instructions to run again but does not by itself pull a newer base image; use --pull when freshness of FROM matters. Build cache mounts can speed package downloads, but the build must still succeed when that cache is empty because cache contents are disposable optimization data.
Add one dependency, rebuild twice, then edit only server.js and rebuild again. Read which steps say CACHED.
Lesson completed