Difficulty: Advanced
How do Docker image layers and the Copy-on-Write (CoW) mechanism work, and what are the practical consequences?
A Docker image is an ordered stack of read-only layers, each one a filesystem diff produced by an instruction like RUN, COPY or ADD. When you start a container, Docker adds a thin writable layer on top and presents the union of all layers as one filesystem. Files are shared from the read-only layers until a container modifies one; only then is that file copied up into the writable layer (Copy-on-Write), so many containers can share the same image on disk.
On Linux the classic storage driver is overlay2, built on the kernel's OverlayFS. Recent Docker Engine releases default fresh installs to the containerd image store, which uses containerd's overlayfs snapshotter; the mechanism is the same.
Each layer is content-addressed by a SHA-256 digest, so two images built on the same node:22-alpine base store that base only once, and docker pull skips layers it already has.
That last point catches people in Dockerfiles too. RUN apt-get install ... followed by a separate RUN rm -rf /var/lib/apt/lists/* does not shrink the image, because the files still live in the earlier layer. Cleanup has to happen in the same RUN that created the files.
npm ci after copying only package*.json) before frequently changing ones (COPY . .) so rebuilds reuse cached layers.docker history <image> lists each layer, its size and the instruction that created it. Instructions like ENV, EXPOSE and CMD only change metadata and show 0B.docker ps -s shows each container's writable layer size plus the virtual size including the image.docker image inspect -f '{{json .RootFS.Layers}}' <image> prints the layer digests.# Start two containers from the same image
docker run -d --name a nginx:1.27
docker run -d --name b nginx:1.27
# Modify a file that lives in an image layer, in container a only
docker exec a sh -c 'echo "# edited" >> /etc/nginx/nginx.conf'
# docker diff shows the copied-up file in container a only
docker diff a | grep nginx.conf
docker diff b | grep nginx.conf || echo "b untouched"
# Writable layer sizes per container
docker ps -s --filter name=a --filter name=b
Editing the config in container a copies that file into a's writable layer; container b still reads the original from the shared image layer.
# Dockerfile (bad): the apt lists are still stored in the first layer
RUN apt-get update && apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*
# Dockerfile (good): created and removed in one layer
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
A delete in a later layer only adds a whiteout, so the bytes still ship with the image. Combining the steps keeps them out of every layer.
Image layers, Copy-on-Write, OverlayFS, overlay2, Whiteout files