appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Layers and build caching

Lesson 1 of 411 minIntermediate

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.

Slow: any code change reinstalls dependencies
FROM node:22-slim
WORKDIR /app
COPY . .
RUN npm ci
CMD ["node", "server.js"]
Fast: dependencies are cached until package files change
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.

.dockerignore
.git
node_modules
.env
*.log
dist

Keep 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, not latest) 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.

1. Why copy package.json before the rest of the source?
2. You delete a large file in a later RUN. What happens to the image size?
Hintdocker build -t name:tag .

Key terms