Layers and build caching
Order a Dockerfile so rebuilds take seconds, not minutes.
Each instruction in a Dockerfile creates a layer. Docker caches layers. When an instruction and everything before it are unchanged, it reuses the cached layer. The first changed instruction invalidates all the ones after it.
FROM node:22-slim
WORKDIR /app
COPY . .
RUN npm ci
CMD ["node", "server.js"]FROM node:22-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
CMD ["node", "server.js"]Rule: put what changes least at the top (base image, system packages, dependency files) and what changes most (your source code) at the bottom.
.dockerignore
Without it, COPY . . sends everything to the builder, including .git, node_modules and local secrets.
.git
node_modules
.env
*.log
distKeep layers small
- Combine commands that must go together:
RUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*. - A file deleted in a later layer still takes space in the earlier one. Clean in the same
RUN. - Pin base image versions (
node:22-slim, notlatest) for repeatable builds.
CarefulNever COPY secrets such as .env or private keys into an image, even if you delete them in a later step. They remain in the layer history and anyone who gets the image can extract them.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.