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 package.json package-lock.json ./
RUN npm ci

COPY src ./src
COPY public ./public

RUN npm run build

Bad Code

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

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.