The build cache

How the order of instructions saves minutes on every build.

On a repeated build Docker reuses finished layers. It goes through the instructions from top to bottom and checks for each one whether anything has changed: the instruction text and, for COPY, the contents of the copied files. As long as nothing has changed, the layer comes from the cache. As soon as one instruction changes, it and every instruction below it run again.

Hence the main rule: put what changes rarely higher up and what changes often lower down. Dependencies change rarely, code changes all the time. So first you copy only the file with the dependency list and install the dependencies, and only then copy the whole code. Then editing one line of code does not force all packages to be downloaded again.

A slow order, where any change in the project resets the package installation cache:

COPY . .
RUN npm ci

A fast order, where installation is redone only when the dependency files change:

COPY package.json package-lock.json ./
RUN npm ci
COPY . .

The second helper is .dockerignore. It works like .gitignore and removes files from the build context: the node_modules folder, .git, logs, local configuration files. A smaller context is sent to the Docker daemon faster, and random changes in junk files do not reset the COPY . . cache.

.git
node_modules
*.log
.env

A common mistake is to refresh packages with a separate line such as RUN apt-get update. Its layer gets cached, and a month later the next line, RUN apt-get install, works with an outdated package list. Refreshing the list and installing are written in one instruction: RUN apt-get update && apt-get install -y curl.

Practice

  1. Order of instructions

    Which order gives a fast rebuild when the code is edited often?

    • COPY . . and then installing dependencies
    • Copying the dependency files, installing, then COPY . .
    • Installing dependencies in CMD at every start
    • The order does not affect the cache
  2. What goes into .dockerignore

    What is sensible to add to .dockerignore in a typical project? Mark all.

    • .git
    • node_modules
    • The application source code
    • .env with local secrets
  3. What gets rebuilt

    A Dockerfile has five instructions. A file copied by the third instruction, a COPY, was changed. How many instructions run again? Answer with a number.