15 min read
Docker layers and the build cache, explained
In one sentence: A Docker image is a stack of read-only layers: each step of the Dockerfile that changes files adds one. When you build again, Docker reuses from its cache every step that hasn't changed, up to the first one that has: that one and every step after it run again. That's why what rarely changes goes at the top.
What you will learn
- Read the layers of an image with docker history and tell the instructions that add a layer from the ones that only store data.
- Explain what the build cache reuses and why one change repeats every step after it.
- Order a Dockerfile so that changing the code doesn't repeat the install of the dependencies.
- Recognize the sha256 fingerprint of an image and know that the same content always gives the same one.
Before you start, read: 01-containers.md
The problem
Section titled “The problem”Imagine Ana puts the shop’s API in an image. She changes a sentence in a file in src/, builds the image again and waits: Docker reinstalls the 161 MB of dependencies. With every change, all over again.
Luis has the same files and almost the same recipe: one more line, and a different order. His image rebuilds in a second and comes out the same as Ana’s.
Why does the order make such a difference? Because Docker builds an image in layers, and keeps each layer to reuse it next time. Almost every rule of a good Dockerfile comes from that.
The analogy
Section titled “The analogy”The analogy
Think of a bakery that makes layer cakes. At the bottom goes a store-bought sponge, then cream, then fruit, and on top the decoration. Each layer goes on top of the one before.
If the customer changes the decoration, the baker keeps the cake and redoes only the top layer. If they change the cream, the baker has to take off the fruit and the decoration, even though they haven’t changed, because they’re on top. That’s why a good baker puts on top what customers change most often.
An image is that cake: the sponge is the base image, each layer of the cake is a layer of the image, and changing one means redoing the ones above it.
Where the analogy breaks down
- Two cakes need two sponges. Two images built on the same base store its layers only once.
- The baker sees what has changed. Docker doesn’t look at what each step does: it compares the text of the instruction and the fingerprint of the files it copies.
- A layer on top can cover a file from a layer below, but not remove it: the image doesn’t get smaller by deleting something in a later step.
How it really works
Section titled “How it really works”A DockerfileThe text file with the recipe for a Docker image, one instruction per line. It says which image to start from, which files to copy, which commands to run while building it and which program each container starts. docker build reads it from top to bottom, and each step that changes files adds a layer.Go to definition is the recipe of an image: a text file with one instruction per line, which Docker runs from top to bottom. You’ll write the shop’s in lesson 3.
An image is a stack of layers
Section titled “An image is a stack of layers”node:26-slim is the image your API will start from: Node 26 on a minimal Debian. docker history shows the steps it was built with:
The steps of node:26-slim
docker history node:26-slimWhat you will see:
IMAGE CREATED CREATED BY SIZE COMMENT193fe51b64e7 5 days ago CMD ["node"] 0B buildkit.dockerfile.v0<missing> 5 days ago ENTRYPOINT ["docker-entrypoint.sh"] 0B buildkit.dockerfile.v0<missing> 5 days ago COPY docker-entrypoint.sh /usr/local/bin/ # … 20.5kB buildkit.dockerfile.v0<missing> 5 days ago RUN /bin/sh -c ARCH= OPENSSL_ARCH= && dpkgAr… 180MB buildkit.dockerfile.v0<missing> 5 days ago ENV NODE_VERSION=26.11.1 0B buildkit.dockerfile.v0<missing> 5 days ago RUN /bin/sh -c groupadd --gid 1000 node &&… 69.6kB buildkit.dockerfile.v0<missing> 9 days ago # debian.sh --arch 'arm64' out/ 'trixie' '@1… 110MB debuerreotype 0.17If you don’t have the image, download it first with docker pull node:26-slim.
CREATED BYis the instruction of each step, cut short with…. With--no-trunc(no truncate) it comes out whole.SIZEis what the step added, uncompressed.<missing>isn’t an error: those steps were built on Docker’s machines, and you only downloaded the result.
Your dates, IDs and sizes will be different: the image is updated often. On a PC you’ll see amd64 instead of arm64.
You read it from the bottom up, in the order it was built:
| Step | What it does | Size |
|---|---|---|
# debian.sh … 'trixie' |
A minimal Debian 13 (“trixie”): the base | 110 MB |
RUN … groupadd … node |
Creates the User (in Linux)An identity on the system, with a name and a number. Each person has their own, and each program on a server usually has another of its own. Every file has a user as its owner, and every process runs on behalf of one.Go to definition node |
69.6 kB |
ENV NODE_VERSION=26.11.1 |
Notes which version of Node it installs | 0 B |
RUN … dpkgArch … |
Downloads Node 26, checks its signature and installs it | 180 MB |
COPY docker-entrypoint.sh … |
Copies a startup script | 20.5 kB |
ENTRYPOINT and CMD ["node"] |
What to run when a container starts | 0 B |
Each step with a size is a Layer (of an image)Each of the read-only pieces that make up a Docker image. It holds the files that one step of the image’s recipe added, changed or deleted, and the layers stack up to form the container’s files. It’s named by the fingerprint of its content, so several images share the layers that are identical and they’re stored only once.Go to definition: a read-only bundle of files with what that step added, changed or deleted. Seven steps and four layers, which add up to about 290 MB uncompressed. What gets downloaded is compressed: 88 MB, the CONTENT SIZE column of docker image ls you saw in lesson 1.
Some instructions add no layer
Section titled “Some instructions add no layer”Only the steps that touch files create a layer:
RUNruns a command during the build, likeapt-get install, and saves what changed on the disk.COPYcopies files from your computer into the image.WORKDIRchooses the working folder and, if it doesn’t exist, creates it: a layer of a few kB.
The others, like ENV, CMD, ENTRYPOINT, EXPOSE or USER, only store data in the image’s record, a small configuration file: that’s why they show 0B. Even so, they count for the cache.
The layers stack up, and the container writes in its own
Section titled “The layers stack up, and the container writes in its own”When you start a container, Docker puts the layers one on top of another and adds the writable layer from lesson 1:
- Container layerwritable; goes away with docker rm
on top of
- COPY docker-entrypoint.sh20.5 kB, read-only
on top of
- RUN: installs Node 26180 MB, read-only
on top of
- RUN: creates the user node69.6 kB, read-only
on top of
- Minimal Debian 13110 MB, read-only
Inside, the program sees a single folder / with everything together. When it looks for a file, Docker searches from the top down and gives it the first one it finds. If the program changes a file from a lower layer, Docker first copies it to the container’s layer and changes it there: the lower layers are never touched.
Deleting works the same way: the top layer gets a mark that says “this file is gone.” The file disappears from view, but it still takes up space in the lower layer.
Several images share the same layers
Section titled “Several images share the same layers”A layer doesn’t belong to one image: it’s stored once, and each image that needs it points to it in its list. If you build three images on node:26-slim, its four layers are on your disk only once, and docker pull doesn’t download the ones you already have.
Each layer is named by its fingerprint
Section titled “Each layer is named by its fingerprint”How does Docker know that two layers are the same? By their fingerprint: a SHA-256 HashA short, fixed-size summary calculated from some data, like a fingerprint. The same data always gives the same hash, and the smallest change gives a completely different one. Git calls each commit by its hash.Go to definition of their content, the same idea as the hash that names each commit in Git. The same bytes always give the same fingerprint, and one different byte gives a completely different one.
The whole image has one too, the digest:
The fingerprint of node:26-slim
docker image ls --digests node:26-slimWhat you will see:
REPOSITORY TAG DIGEST IMAGE ID CREATED SIZEnode 26-slim sha256:193fe51b64e77981119c98c2002c9e32a70e2f006fb4d25068ce0558998917f0 193fe51b64e7 5 days ago 378MB--digests adds the DIGEST column: sha256: and 64 characters. It’s the fingerprint of the record that describes the image, which points to each layer by its fingerprint: if one byte of any layer changes, the digest changes. The IMAGE ID is its first 12 characters.
With --digests, the table goes back to its old format. Its SIZE, 378 MB, is what it takes up on your disk: the uncompressed layers plus the download, which Docker keeps too. Your digest will be different if your image is newer, not because of your processor.
Same content, same fingerprint, on any computer in the world. A tag like 26-slim may point to another image tomorrow; node:26-slim@sha256:193f… is always exactly this one. Lesson 8 uses it to pin versions.
The build cache reuses what hasn’t changed
Section titled “The build cache reuses what hasn’t changed”When you build an image, Docker keeps each layer in its Build cacheThe layers Docker keeps from earlier builds so it doesn’t repeat work. A step is reused if the one before it was reused and its own hasn’t changed, neither its text nor the files it copies. As soon as one changes, that step and every step after it run again.Go to definition. The next time, it goes through the Dockerfile from top to bottom and, at each step, asks itself two things:
- Did I reuse the previous step?
- Is this step the same as last time? For a
RUN, anENVor aCMD, the same means the same text. For aCOPY, also the same files: Docker calculates the fingerprint of their content and compares it.
If both answers are yes, it reuses the stored layer: CACHED, zero seconds. At the first step that changes, it runs it, and from there it also runs every step after it, even if they don’t use what changed. Each layer is built on top of the previous one: if the one below changes, the one above is no longer valid, like the layer of the cake.
Docker never looks at what a RUN does. If the text is the same, it reuses it, even if the command would give a different result today.
Why package.json goes before the code
Section titled “Why package.json goes before the code”In a Node API, the slow step is npm ci: it installs exactly the versions in the lockfile package-lock.json (you saw it in Phase 3). Its layer is the biggest one: 161 MB in the shop.
Compare the two possible orders:
| Ana’s order | Luis’s order | |
|---|---|---|
| First | COPY . .: copies everything |
COPY package*.json ./: copies package.json and package-lock.json |
| Then | RUN npm ci |
RUN npm ci |
| At the end | COPY . .: copies the rest |
|
You change a file in src/ |
What COPY . . copies changes, so npm ci runs again |
npm ci is reused: its files haven’t changed. Only the last COPY runs again |
The * in package*.json stands for any text, as in the terminal. The general rule: what rarely changes, at the top; what you change often, at the bottom. The dependencies change when you add one; the code, every day.
Try it
Section titled “Try it”The goal: find out how much time Luis’s order saves you, first with the shop’s Dockerfile in the lab and then with an image of your own, built for real.
In the lab
Section titled “In the lab”The lab shows the shop’s Dockerfile, the one from lesson 3, next to the layers it builds, with sizes and seconds from real builds. It follows Luis’s order, but copies the files by name and, with them, .npmrc, npm’s settings: lesson 3 explains why.
lab · Docker layers
Dockerfile
Without its comments.
WORKDIR /appCOPY package.json package-lock.json .npmrc ./copies package.json, package-lock.json, and .npmrc (npm’s settings)RUN npm ciCOPY . .copies everything not in .dockerignore
Layers
From the base to the last layer, in the order they stack up.
node:26-slim@sha256:193fe51b64e7…: 4 layers, 289.2 MBThe base image. It is downloaded once and never rebuilt.- line 2
WORKDIR /app8.2 kBnot built - line 3
COPY package.json package-lock.json .npmrc ./106.5 kBnot built - line 4
RUN npm ci160.8 MBnot built - line 5
COPY . .745.5 kBnot built
- Image size
- 450.9 MB (base 289.2 MB + your layers 161.7 MB)
- Time of the last build
- not built yet
- Changes since the last build
- none
This is the shop’s Dockerfile, and next to it the layers it builds. Nothing is built yet: press “Build”.
Real sizes from docker history and seconds from docker build, measured on 2026-10-14.
- Press “Build”: the first time, with no cache, every step runs. Notice which one is slow.
- Press “Change a file in src/” and then “Rebuild”. Which layers are reused?
- Do the same with “Change package.json”. From which line does everything run again?
- Switch “Order” to “wrong”, Ana’s, build and repeat step 2. Compare the time.
- Set “Multi-stage” to “yes”: you’ll see which parts don’t reach the final image. Lesson 4 explains it.
In your terminal: an image with two files
Section titled “In your terminal: an image with two files”Now, the same idea with a small image. The outputs are from Docker Engine 29 on a Mac, inside a virtual machine with Linux; we captured them with another image name, changed to hello, and nothing else changes. Your IDs, fingerprints, sizes and times will be different.
Create the folder:
mkdir -p ~/backend-course/phase-7/hellocd ~/backend-course/phase-7/helloInside it, create with your editor a file hello.js with this line:
console.log("Hello from Ana and Luis's shop");And another one, called Dockerfile, with no extension:
FROM node:26-slimRUN apt-get update && apt-get install -y --no-install-recommends curlWORKDIR /appCOPY hello.js ./CMD ["node", "hello.js"]Lesson 3 explains each instruction. For now:
FROMstarts fromnode:26-slim, with its four layers.RUNinstallscurlwithapt, as in Phase 1. It plays the part ofnpm ci: it takes a while, and what it installs rarely changes.WORKDIRandCOPYcreate/appand copy your file there.CMDsays what to run at startup.
1. Build the image
docker build --progress=plain -t hello .What you will see:
…#5 [1/4] FROM docker.io/library/node:26-slim@sha256:193fe51b64e77981119c98c2002c9e32a70e2f006fb4d25068ce0558998917f0#5 resolve docker.io/library/node:26-slim@sha256:193fe51b64e77981119c98c2002c9e32a70e2f006fb4d25068ce0558998917f0 0.0s done#5 CACHED
#6 [2/4] RUN apt-get update && apt-get install -y --no-install-recommends curl…#6 DONE 4.9s
#7 [3/4] WORKDIR /app#7 DONE 0.0s
#8 [4/4] COPY hello.js ./#8 DONE 0.0s
#9 exporting to image#9 exporting layers#9 exporting layers 0.9s done#9 exporting manifest sha256:5f9871a639843ec3a9ccded1e460c0a2e17214e96c7b6a62bf6008544f538f91 done…#9 naming to docker.io/library/hello:latest done…Word by word:
docker buildbuilds an image from theDockerfilein a folder.--progress=plainwrites each step on its own lines. Without it, Docker draws a summary that keeps rewriting itself and folds up when it finishes.-t hello(from tag) gives the image a name. With no tag, Docker addslatest..is the current folder: its files are the only onesCOPYcan copy.
We’ve removed (…) the first lines, [internal], which read the Dockerfile and your files, and the ones from apt. Look at [2/4]: step 2 of 4 took 4.9 seconds, and the others almost nothing. In FROM, the tag has turned into a digest. Note down the exporting manifest sha256:5f98…: it’s the fingerprint of the record that describes your image.
If you get "/hello.js": not found, the file isn’t in the folder or has another name: check with ls.
2. Build it again, without changing anything
docker build --progress=plain -t hello .What you will see:
…#6 [2/4] RUN apt-get update && apt-get install -y --no-install-recommends curl#6 CACHED
#7 [3/4] WORKDIR /app#7 CACHED
#8 [4/4] COPY hello.js ./#8 CACHED
#9 exporting to image#9 exporting layers done#9 exporting manifest sha256:5f9871a639843ec3a9ccded1e460c0a2e17214e96c7b6a62bf6008544f538f91 done…Every step says CACHED: nothing has changed, so Docker runs none of them. And the fingerprint is the same 5f98… as before: same content, same fingerprint.
Other fingerprints we removed do change: next to the image, Docker keeps a note with the time of the build. That’s why the IMAGE ID changes every time.
Now change the text of hello.js with your editor, for example to "Hello from Ana and Luis's shop. We open on Monday.", and save it.
3. Change the code and rebuild
docker build --progress=plain -t hello .docker run --rm helloWhat you will see:
…#6 [2/4] RUN apt-get update && apt-get install -y --no-install-recommends curl#6 CACHED
#7 [3/4] WORKDIR /app#7 CACHED
#8 [4/4] COPY hello.js ./#8 DONE 0.0s…Hello from Ana and Luis's shop. We open on Monday.RUN and WORKDIR are still cached; only COPY hello.js runs, because the file’s fingerprint has changed. It’s Luis’s order: the 4.9 seconds of apt aren’t repeated. docker run --rm hello starts the new image.
If RUN doesn’t say CACHED, check that you haven’t touched its line: one extra space is already a different text.
4. How much space does it really take?
docker history hellodocker system df -v | grep -E 'REPOSITORY|hello|26-slim'What you will see:
IMAGE CREATED CREATED BY SIZE COMMENT3804e51c192b 59 seconds ago CMD ["node" "hello.js"] 0B buildkit.dockerfile.v0<missing> 59 seconds ago COPY hello.js ./ # buildkit 12.3kB buildkit.dockerfile.v0<missing> About a minute ago WORKDIR /app 8.19kB buildkit.dockerfile.v0<missing> About a minute ago RUN /bin/sh -c apt-get update && apt-get ins… 35.9MB buildkit.dockerfile.v0<missing> 5 days ago CMD ["node"] 0B buildkit.dockerfile.v0<missing> 5 days ago ENTRYPOINT ["docker-entrypoint.sh"] 0B buildkit.dockerfile.v0<missing> 5 days ago COPY docker-entrypoint.sh /usr/local/bin/ # … 20.5kB buildkit.dockerfile.v0<missing> 5 days ago RUN /bin/sh -c ARCH= OPENSSL_ARCH= && dpkgAr… 180MB buildkit.dockerfile.v0<missing> 5 days ago ENV NODE_VERSION=26.11.1 0B buildkit.dockerfile.v0<missing> 5 days ago RUN /bin/sh -c groupadd --gid 1000 node &&… 69.6kB buildkit.dockerfile.v0<missing> 9 days ago # debian.sh --arch 'arm64' out/ 'trixie' '@1… 110MB debuerreotype 0.17REPOSITORY TAG IMAGE ID CREATED SIZE SHARED SIZE UNIQUE SIZE CONTAINERShello latest 3804e51c192b About a minute ago 433MB 375.4MB 57.56MB 0node 26-slim 193fe51b64e7 5 days ago 378MB 375.4MB 2.235MB 0docker history hello shows your four steps on top of the seven of node:26-slim. Your RUN added 35.9 MB; your COPY, a few kB.
docker system df (disk free) counts what Docker takes up on your disk, and -v (verbose) breaks it down by image. grep -E 'A|B|C' keeps the lines with any of the three texts (lesson 3 of Phase 1). SHARED SIZE, 375.4 MB, is the layers of node:26-slim: they’re in both images and on your disk only once. UNIQUE SIZE is what belongs to each one.
We’ve adjusted the space between columns, which other images widened on our machine.
Challenge: in the Dockerfile, move the RUN line down below COPY hello.js ./, in Ana’s order. Build, change the sentence in hello.js again and build again. Which steps run again in the second build, and why?Show answer
In the second build, COPY and everything after it run again, apt included:
#7 [3/4] COPY hello.js ./#7 DONE 0.0s
#8 [4/4] RUN apt-get update && apt-get install -y --no-install-recommends curl…#8 DONE 5.1sapt doesn’t use hello.js, but it comes after a step that changed, and Docker doesn’t look at what each command does. It’s Ana’s order: every change to the code pays the seconds of the install.
To finish, delete the image:
5. Clean up
docker image rm helloWhat you will see:
Untagged: hello:latestDeleted: sha256:3804e51c192b3461809aa9a44f015e28774aa3b3af364372748f16ace5b28a08node:26-slim stays: you’ll use it in lesson 3. So does the build cache, and it takes up space: docker system df shows it in the Build Cache row.
You have already seen it
Section titled “You have already seen it”- The lines of
docker pull. In lesson 1, each line with a code was a piece of the image, almost all of them layers, named by the start of its fingerprint. - HTTP caching. The
ETagfrom Phase 2 is a fingerprint of the content, to know whether it has changed without downloading it again. The build cache does the same with your files.
Common mistakes
Section titled “Common mistakes”- Copying everything before installing. With
COPY . .beforenpm ci, every change to the code reinstalls the dependencies. - Deleting in a separate step.
RUN rmon another line doesn’t make the image smaller: the file is still in the layer below. You delete it in the sameRUNthat creates it, as in lesson 4. - Expecting the cache to know what a
RUNdoes.RUN apt-get updatecan stayCACHEDfor months. To build from scratch,docker build --no-cache. - Copying too much.
COPY . .also takesnode_modulesor your.env, and if they change, they invalidate the cache. A.dockerignorefile leaves them out (lesson 3). - Adding up the sizes from
docker image ls. Shared layers count in each image, but they’re on the disk once: look atdocker system df.
Summary
Section titled “Summary”- An image is a stack of read-only layers.
RUN,COPYandWORKDIRadd one;ENV,CMDorEXPOSEonly store data in its record. - The container sees the layers as a single folder and writes in its own. Deleting in a layer on top hides the file, but doesn’t free its space.
- Each layer and each image are named by the SHA-256 fingerprint of their content: same content, same fingerprint. That’s why several images share layers.
- The cache reuses a step if the previous one was reused and its own hasn’t changed: the same text and, for a
COPY, the same files. From the first change on, everything runs again. - What rarely changes goes at the top:
COPY package*.jsonandnpm cibefore copying the code.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Understanding the image layers and Using the build cache, from the Docker documentation.
- Cache invalidation and Optimize cache usage: what each instruction invalidates and how to order a Dockerfile.
- The
docker historyreference. - Descriptor, from the OCI image specification: how digests are calculated and used.