Sub topic 12
Union Filesystems and Copy-on-Write Under the Container
This chapter explains what happens on disk when a container starts. It covers how read-only image layers and one writable layer combine into a single filesystem view, and how writes, deletes, and volumes behave in that model. It assumes you know docker run and docker build, can read a Dockerfile, and know that an image is a stack of layers.
From stacked layers to one filesystem
An image is a stack of read-only layers. A process inside a container does not see a stack. It sees one ordinary directory tree. A union filesystem produces that view. It merges several directories, called branches, into one mount point.
Docker's default storage driver on modern Linux is overlay2, which uses the kernel's OverlayFS. OverlayFS uses these terms:
| OverlayFS term | Role in Docker |
|---|---|
| `lowerdir` | The read-only image layers, listed from top to bottom |
| `upperdir` | The container's writable layer |
| `workdir` | Scratch space OverlayFS needs for atomic operations |
| `merged` | The unified view mounted as the container's root filesystem |
When the container starts, Docker mounts these directories together. You can see the result on a Linux host:
docker run -d --name demo nginx:alpine
docker inspect --format '{{json .GraphDriver.Data}}' demoThe output has keys named LowerDir, UpperDir, WorkDir, and MergedDir. LowerDir is a colon-separated list of layer directories under /var/lib/docker/overlay2/. Each image layer is one entry in that list.
Lookup order: top wins
When a process opens /etc/nginx/nginx.conf, OverlayFS searches the branches from the top down. It checks the writable layer first, then the highest image layer, and so on down. The first branch that contains the path supplies the file. Lower versions of the same path stay on disk but are hidden.
This is why a later Dockerfile instruction can "replace" a file from an earlier one. The new copy sits in a higher layer and shadows the old one. The old bytes remain in the lower layer. The previous chapter on layer size pitfalls relies on this fact.
Directories merge differently from files. If two layers both contain /app/, the merged /app/ shows the union of their entries. If both layers contain /app/config.json, only the highest one is visible.
Copy-on-write
Image layers are read-only, and many containers can share them. So a container cannot modify a lower file in place. OverlayFS uses copy-on-write, often shortened to CoW:
- A process opens a file that exists only in a lower layer, and it opens the file for reading. OverlayFS serves it directly from the lower layer. Nothing is copied.
- The process opens the same file for writing, or changes its metadata, such as permissions. OverlayFS first copies the whole file up into the writable layer. This step is called copy-up.
- The write happens on the copy. From then on, the copy in the writable layer hides the original.
Two consequences follow from this.
- Reads are cheap, first writes can be costly. Copy-up copies the entire file, even if you change one byte. Appending a line to a 2 GB database file in a lower layer first copies 2 GB. Later writes to that file go straight to the copy and are fast.
- Unchanged files cost nothing. A container that only reads its image adds almost no disk space. A hundred containers from one image share one set of lower layers.
You can watch copy-up with docker diff, which lists changes in the writable layer:
docker run -d --name cow-demo alpine sh -c 'echo "# edited" >> /etc/hostname; sleep 300'
docker diff cow-demo
docker rm -f cow-demoThe output marks entries with A (added), C (changed), or D (deleted). /etc/hostname appears because the container modified it. Files the container only read do not appear.
Deletes: whiteouts
A read-only layer cannot lose a file. So when a layer "deletes" something, the filesystem records a marker saying the path is gone. OverlayFS uses two kinds of markers:
- Whiteout: a special character device file with the same name as the deleted file. It hides the same path in all lower layers.
- Opaque directory: a directory carrying an attribute that tells OverlayFS to ignore every lower layer's contents for that path. It is used when a directory is deleted and then recreated.
Image layers are stored as tar archives, which have no native way to express a delete. The OCI image format therefore encodes a deletion as an empty file named .wh.<name>. An opaque directory is encoded as a file named .wh..wh..opq inside it. The runtime translates between these forms and the OverlayFS markers.
This is the exact mechanism behind the bloat problem you saw earlier. The line RUN tar -xzf big.tar.gz -C /opt && rm big.tar.gz writes a whiteout for big.tar.gz into its own layer. The earlier layer that downloaded the archive still stores every byte. Hiding a path and freeing its bytes are different operations, and a layered, immutable stack only supports the first.
The writable layer is temporary
The writable layer belongs to one container. When you run docker rm, Docker deletes it. Stopping a container does not delete it, so a stopped container still holds its changes until removal. Starting a new container from the same image gives you a fresh, empty writable layer.
Writing into the writable layer has three drawbacks:
- Lifetime. The data disappears with the container.
- Speed. Every write passes through the union filesystem. Copy-up adds cost on the first write, and heavy small-file or database workloads can feel it.
- Sharing. Other containers cannot easily reach this data.
Docker offers two ways to avoid the writable layer for data that matters.
| Option | What it is | Typical use |
|---|---|---|
| Volume | Storage managed by Docker, mounted into the container at a path | Database files, uploads, anything that must outlive the container |
| Bind mount | A host directory mounted into the container | Source code during development, host config files |
| `tmpfs` mount | Memory-backed storage that is never written to disk | Scratch data and secrets that must not persist |
A mount replaces whatever the image has at that path for the lifetime of the container. The mount is not part of the union filesystem. Reads and writes bypass OverlayFS entirely and go straight to the underlying filesystem or memory.
docker volume create appdata
docker run --rm -v appdata:/data alpine sh -c 'echo saved > /data/note.txt'
docker run --rm -v appdata:/data alpine cat /data/note.txtThe second container prints saved, even though the first container and its writable layer are gone.
Measuring the writable layer
docker ps --size reports two numbers for each container. The first is the size of the writable layer. The second, labelled "virtual", is the writable layer plus the shared read-only image layers.
docker ps --all --size --format 'table {{.Names}}\t{{.Size}}'A large first number means the container is writing a lot into its own layer. That is usually a sign that a log file, cache, or data directory should be on a volume.
Edge cases and gotchas
- Renaming a directory. A rename of a directory that exists in a lower layer is not a cheap metadata change on OverlayFS. Depending on configuration, the kernel can return
EXDEV("cross-device link"), and tools such asmvfall back to copying files one by one. In a Dockerfile, a recursivemvof a large directory can therefore duplicate it into a new layer. chmodandchowncount as writes. RunningRUN chown -R app:app /appover files from earlier layers copies every one of them into the new layer, even though the contents do not change. UseCOPY --chown=app:appinstead, which sets ownership while copying.- Hard links. Hard links across layers can break. A file with two names in a lower layer can become two independent copies after copy-up of one of them. Rely on
indexandnfs_exportsettings only if you know your kernel configuration. - Other storage drivers.
overlay2is the default, but Docker supports others, such asbtrfs,zfs, andfuse-overlayfsfor rootless setups. Their copy-up behavior differs. Some work per block instead of per file. Checkdocker infofor theStorage Driverline. - Containerd image store. Newer Docker versions can use containerd's snapshotter for image storage. The OverlayFS model described here still applies, but the paths on disk differ from
/var/lib/docker/overlay2.
The following Dockerfile shows the chown trap and its fix:
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# Bad: rewrites ownership metadata on every file, duplicating them in a new layer.
# RUN chown -R node:node /app
# Better: set ownership as the files are first written.
COPY --chown=node:node . .
USER node
CMD ["node", "dist/server.js"]Note that the npm ci output is still owned by root in this version. If the application needs to write into node_modules, give that step the right user instead. For a read-only dependency tree, root ownership is fine and often preferable.
Summary of the model
- A container's root filesystem is an OverlayFS mount: read-only image layers below, one writable layer on top.
- Lookups go top-down, and the first match wins.
- A first write to a lower-layer file triggers a full-file copy-up.
- Deletes are whiteout markers. They hide data but never free it in lower layers.
- Volumes and bind mounts bypass the union filesystem and persist beyond the container.
Exercise
A Dockerfile has RUN apt-get install -y build-essential in one step, then RUN rm -rf /var/cache/apt /usr/share/doc in the next. The image size barely changes. Using whiteouts and layers, explain why. Then name one change that would reduce the size.
Show answer
The first RUN stores the installed files and caches in its own read-only layer. The second RUN does not remove those bytes. It adds a layer containing whiteout markers that hide the paths in the merged view, so the lower layer still holds all the data and the image still carries it. To shrink the image, run the install and the cleanup in the same RUN instruction so the deleted files are never written into any layer. A multi-stage build that copies only the needed output into the final stage also works.
Exercise
A container reads a 500 MB file from its image, then appends one line to it. What does docker diff show for that file, and how much extra disk space does the container's writable layer use after the append?
Show answer
docker diff shows the file as C (changed). The writable layer uses about 500 MB more, because OverlayFS copies the whole file up before the write, even though only one line changed. The read alone used no extra space.