Sub topic 2
Layers: how images are stacked
This chapter assumes you can run docker run and docker build, and that you know a container is an isolated process with its own filesystem view. Here you will learn how an image's filesystem is split into layers, how those layers combine into one view, and why that affects image size and container behavior.
An image is a stack of filesystem changes
A Docker image does not store one big filesystem. It stores an ordered list of layers. A layer is a set of file changes: files added, files modified, and files deleted, relative to the layer below it.
Layers are read-only once built. The first layer is usually the base image's root filesystem. Each later layer records only what its instruction changed.
When Docker starts a container, it merges the layers into one directory tree. Files in higher layers hide files at the same path in lower layers. The process inside the container sees a single ordinary filesystem.
Which instructions create layers
Instructions that change the filesystem produce a layer. Instructions that only record settings produce metadata in the image config and add no files.
| Instruction | Effect |
|---|---|
| `FROM` | Brings in the layers of the base image |
| `RUN` | Runs a command; the files it changes become a layer |
| `COPY`, `ADD` | Adds files from the build context as a layer |
| `ENV`, `CMD`, `ENTRYPOINT`, `EXPOSE`, `LABEL`, `USER` | Metadata only, no file changes |
| `WORKDIR` | Metadata, and creates the directory if it is missing |
Metadata-only steps still show up in docker history, but with a size of 0B.
Inspecting layers
Create a small project and build it. The dd command writes a 50 MB file, which makes layer sizes easy to see.
mkdir layers-demo && cd layers-demo
echo "hello" > hello.txt
cat > Dockerfile <<'EOF'
FROM alpine:3.20
COPY hello.txt /hello.txt
RUN dd if=/dev/zero of=/big.bin bs=1M count=50
RUN rm /big.bin
CMD ["cat", "/hello.txt"]
EOF
docker build -t layers-demo:1 .
docker history layers-demo:1
docker image ls layers-demo:1docker history lists one row per instruction, newest first. You should see a row of about 52.4 MB for the dd step, a row near 0B for rm, and a tiny row for COPY. The base image rows appear at the bottom. The docker image ls output reports a size above 50 MB even though /big.bin no longer exists in the running container.
Deleted files still cost space
Layers are read-only, so a later layer cannot remove bytes from an earlier one. When RUN rm /big.bin runs, Docker records a whiteout entry in the new layer. A whiteout is a marker that says "this path is deleted". The merged view hides the file, but the 50 MB still sits in the layer below and is still downloaded when someone pulls the image.
Check this yourself:
docker run --rm layers-demo:1 ls /big.binThe command fails with "No such file or directory", yet the image size is unchanged. The fix is to create and delete the file in the same instruction, so no layer ever contains it:
FROM alpine:3.20
COPY hello.txt /hello.txt
RUN dd if=/dev/zero of=/big.bin bs=1M count=50 && rm /big.bin
CMD ["cat", "/hello.txt"]This matters most for package installs, downloaded archives, and build tools. Clean up in the same RUN that created the mess. For example, use apk add --no-cache on Alpine, or remove package lists in the same RUN on Debian-based images.
Copy-on-write and the container layer
Starting a container adds one thin writable layer on top of the image's read-only layers. The image itself is never changed. This is why you can start many containers from one image without copying it.
Docker uses a union filesystem driver to do the merging. On most Linux installs this is overlay2, which presents the read-only layers as lowerdir, the writable layer as upperdir, and the combined result as merged.
The behavior follows the copy-on-write strategy:
- Reading a file serves it from the highest layer that contains it. No copy happens.
- Creating a file writes it directly into the writable layer.
- Modifying a file that exists in a lower layer first copies the whole file into the writable layer, then changes the copy.
- Deleting a file in a lower layer adds a whiteout in the writable layer.
You can see the writable layer's contents with docker diff:
docker run --name writer layers-demo:1 sh -c 'echo hi > /new.txt'
docker diff writer
docker rm writerThe output lists changes with a prefix: A for added, C for changed, D for deleted. You should see A /new.txt. When you remove the container, the writable layer is removed with it, and the data is gone unless you stored it in a volume.
Copy-on-write has a cost. Modifying a large file that lives in a lower layer copies the entire file first, even for a one-byte edit. Write-heavy workloads, such as databases, should use volumes, which bypass the layered filesystem.
Layers are shared
Layers are identified by a hash of their content (the next chapters on digests and manifests cover this properly). Two images that start with the same base image reference the same base layers. Docker stores each layer once on disk, and a registry transfers only the layers the other side lacks.
Practical consequences:
- Ten services built on
alpine:3.20store the Alpine layers once locally. - Pulling a new version of your app usually downloads only the layers that changed.
docker image lsreports each image's full size, so the sizes of images that share layers add up to more than the real disk use.docker system dfshows actual usage.
Layer order therefore matters. Put the instructions that change rarely (base image, system packages) first, and those that change often (your source code) last. That way a code edit rebuilds and re-transfers only the last layer. The build cache chapter develops this idea.
Common mistakes
- Cleanup in a separate
RUN. The files are already committed to an earlier layer. Combine creation and cleanup with&&. - Copying everything early. A
COPY . .near the top of a Dockerfile makes every later layer depend on every source file. - Counting layers as a cost to minimize. Fewer layers is not the goal. Small layers that do not contain throwaway data are. Merging unrelated steps into one
RUNonly hurts cache reuse. - Storing data in the container layer. It disappears with the container and is slower than a volume.
Exercise
A Dockerfile has RUN apt-get update && apt-get install -y build-essential followed by a separate RUN apt-get remove -y build-essential && rm -rf /var/lib/apt/lists/*. The author expects a smaller image. Does the second instruction shrink it, and how would you change the Dockerfile?
Show answer
No. The first RUN commits the installed packages and package lists into a layer, and the second RUN only adds a layer with whiteouts hiding them. The earlier layer still holds the bytes, so the image size stays about the same and users still download them. Do the install, any build work, the removal, and the rm -rf /var/lib/apt/lists/* in one RUN with &&, or move the build work to a separate build stage so the final image never contains the tools.