Linux Labs

Containers: Docker and compose / Stage 4 of 11

Dockerfile: your own image

Not running Starting usually ~20 s
Leave the lesson

Step 4 of 7 · on a machine · 7 min

The build cache

You will rebuild the image twice and see which steps docker takes ready-made.

docker prints each build step as a line like #6 [2/4] WORKDIR /www, and the last line with the same number tells how the step ended: CACHED, or DONE with the time. Compare two builds of one Dockerfile: without changes and after an edit to index.html.

Exercise · look

Rebuild the image twice

In ~/site, build site:2 once more without changes, then replace v2 with v3 in index.html and build site:3.

First, predict

Which steps will the second build, after the index.html edit, run again?

Now start the exercise, run the command and compare your prediction with the output.

Sign in and start The machine is available after signing in

Before each step docker looks for a ready layer: one built on top of the same previous layer by the same instruction, and for COPY also from the same files. If it finds one, it prints CACHED and skips the step. This is the build cache. The build without changes went through the cache entirely: site:2 kept the same layers.

The index.html edit changed the COPY layer. The steps below are now built on top of the new layer, and there are no ready layers for them: RUN ran again, although its line is the same. The time in site:3's built.txt is new.

That is why things that change often — pages, code — are copied near the end of a Dockerfile, while long steps that do not need those files go higher up: an edit rebuilds only the tail.

Check yourself 1 question

In another Dockerfile, the line RUN date -u '+%F %T' > built.txt comes before COPY index.html .. You edit index.html and rebuild the image. What will built.txt in the new image hold?

  • date does not depend on index.html and writes the time in any step order. Here it does not even run: the step comes from the cache.

  • The previous image does not get in the way: the build runs to the end, with CACHED for the RUN step.

  • RUN comes before COPY: it has the same previous layer and the same line, so docker prints CACHED and does not run date.

docker takes the step above the edit from the cache and does not run it, so built.txt keeps the time of the previous build. That is how the cache saves long steps, and how it can leave their result stale.

Ubuntu 24.04
Loading…