Lesson 2 of 9 · 20m
Image Layers and OverlayFS
Images are stacks of read-only diff layers merged by overlayfs — and understanding the merge explains image size, build caching, and why `rm` doesn't shrink anything.
Pull any image and look at what actually arrived: not a filesystem, but a list of tarballs plus a JSON manifest. Each tarball is a diff — only the files one Dockerfile instruction added or changed. The running container is those diffs stacked and merged by overlayfs, with one thin writable layer on top.
The overlay mount, in one diagram
container view = upperdir (writable, per-container)
+ lowerdir = layer4:layer3:layer2:layer1 (read-only, shared)You can inspect the real thing on a host:
docker inspect nginx --format '{{json .GraphDriver.Data}}' | python3 -m json.tool
# {
# "LowerDir": "/var/lib/docker/overlay2/l1/...:l2/...",
# "UpperDir": "/var/lib/docker/overlay2/<id>/diff",
# "MergedDir": "/var/lib/docker/overlay2/<id>/merged"
# }MergedDir is what the container sees as /. Files in upper layers shadow files with the same path below them. Deleting a file from a lower layer writes a whiteout — a marker file in the upper layer that hides it. The bytes are still down there.
Why rm makes images bigger
FROM ubuntu:24.04
RUN dd if=/dev/urandom of=/bigfile bs=1M count=200
RUN rm /bigfileThis image is 200MB larger than the base. The dd layer permanently contains the file; the rm layer contains only a whiteout. Every image pull, every registry push, every node disk carries the dead weight forever. This is the single most expensive misconception in Dockerfile authorship — secrets baked in then "deleted" this way are still trivially recoverable with docker save + tar.
Layers are shared — that's the point
Two images built FROM ubuntu:24.04 share the base layers on disk and in the registry. A host running fifty containers from one image stores the base layers once. This is why image size and container count are decoupled — and why bloating shared base images hurts disproportionately.
Watch it in action:
docker history nginx:1.27
# IMAGE CREATED BY SIZE
# <missing> /bin/sh -c #(nop) CMD ["nginx" "-g" "daemon… 0B
# <missing> /bin/sh -c #(nop) COPY file:... in / 7kB
# <missing> /bin/sh -c apt-get install ... 61MB0B instructions (CMD, ENV, EXPOSE) are metadata-only layers — they're free. Size lives in the instructions that touch the filesystem.
Field notes
- Never put a secret in any layer, even one you delete later. Use build secrets (
--mount=type=secret) or runtime injection. docker system dfshows real disk cost;docker image lssizes are logical and double-count shared layers.- OverlayFS can't nest cleanly — running Docker-in-Docker on overlay-backed storage needs a volume for
/var/lib/dockeror you get corruption and pain. - Copy-on-write means a container modifying one small file in a big layer copies the whole file up. Writes to huge pre-existing files (databases!) belong on volumes, not in the container layer.
Was this lesson helpful?