Docker

Lesson 03

Layer cache and dependency order

Order Dockerfile instructions so dependency layers are reused when source files change.

Good Code

Dockerfile
FROM node:22-alpine AS app
WORKDIR /app

# Copy dependency files first so npm ci can stay cached.
COPY package.json package-lock.json ./
RUN npm ci

# Source changes happen after dependency install.
COPY src ./src
COPY public ./public

RUN npm run build

Bad Code

Dockerfile
FROM node:22-alpine AS app
WORKDIR /app

# Copying everything first makes any source edit break the install cache.
COPY . .
RUN npm install
RUN npm run build

Review Notes

What to review

Good Code

The good version lets the dependency install layer stay cached when only source files change.

Bad Code

The bad version copies the whole project before installing dependencies. Any source edit can invalidate the expensive install layer.

Takeaways

  • Docker cache follows instruction order, so dependency files should usually be copied before application source.