Lesson 93 · Section 8: Storage
Lesson 93: Storage in Docker: layers, volumes and bind mounts
Where a container's files really live: read-only image layers, one thin writable layer per container, and the three kinds of mount that keep data after the container is gone. The ground work for volumes in Kubernetes. · 16 min read · 4 min video
Official competencies this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
What this lesson is about
The Storage section of the course ends with PersistentVolumes, claims and storage classes. All of them exist to answer one question: where does the data go when the container is gone? That question is easiest to understand on a single machine with Docker, where you can see every directory involved.
This lesson explains two things that people often mix up:
- Storage drivers decide how the image and the container's own file system are stored. This is the layered file system.
- Volumes and mounts decide where data lives that must outlast the container.
The next lesson continues with volume driver plugins, which move a volume from the local disk to external storage. That idea leads directly to the Container Storage Interface in Kubernetes.
How Docker stores images and containers
Where the data is on disk
The Docker daemon keeps its state in one data directory, /var/lib/docker on Linux.
| Directory | What is in it |
|---|---|
/var/lib/docker/volumes | One folder per volume, with the data under _data |
/var/lib/docker/containers | Per container: configuration, the log file, hostname, resolv.conf |
/var/lib/docker/overlay2 | Image layers and container layers, with the classic overlay2 storage driver |
/var/lib/docker/image | The index that says which layers form which image |
/var/lib/containerd | Image content and container snapshots, with the containerd image store |
Layers
Take this Dockerfile:
FROM ubuntu:24.04
RUN apt-get update && apt-get install -y python3 python3-flask
COPY app.py /opt/app/app.py
ENTRYPOINT ["python3", "/opt/app/app.py"]
Every instruction that changes the file system produces a layer: a set of files that were added, changed or
removed compared with the layer below. Instructions such as ENTRYPOINT or ENV change only metadata and add an
empty layer.
docker build -t my-app:1.0 .
docker history my-app:1.0
IMAGE CREATED CREATED BY SIZE
a3f1c9e02b7d 2 minutes ago ENTRYPOINT ["python3" "/opt/app/app.py"] 0B
<missing> 2 minutes ago COPY app.py /opt/app/app.py # buildkit 1.2kB
<missing> 2 minutes ago RUN /bin/sh -c apt-get update && apt-get ins… 146MB
<missing> 3 weeks ago /bin/sh -c #(nop) ADD file:… in / 78.1MB
Layers give Docker three advantages:
- Sharing. A second image built
FROM ubuntu:24.04reuses the 78 MB base layer. It is stored once and pulled once. - Build cache. If you change only
app.py, Docker rebuilds only theCOPYlayer and those after it. The 146 MB package layer comes from the cache. This is why the instructions that change least go first. - Fast start. A new container does not copy the image. It adds one empty layer on top of layers that already exist.
Parts:
- Layer 3: app code (COPY app.py, 1 kB), in Image: read-only, shared
- Layer 2: packages (RUN apt-get, 146 MB), in Image: read-only, shared
- Layer 1: base OS (FROM ubuntu, 78 MB), in Image: read-only, shared
- Container layer (read-write, one per container)
- Merged view (one file system)
- Process (reads and writes /)
Connections:
- Layer 1: base OS to Layer 2: packages: then
- Layer 2: packages to Layer 3: app code: then
- Layer 3: app code to Container layer: on top
- Container layer to Merged view: merged
- Process to Merged view: uses
The container layer and copy-on-write
Image layers are read-only. They have to be, because many containers share them. When Docker creates a container, it adds one more layer on top that is read-write and belongs only to that container. A storage driver, normally one based on the kernel's OverlayFS, merges all layers into a single directory tree, and that tree becomes the container's root file system.
What happens on each kind of access:
| The process... | What the storage driver does |
|---|---|
| Reads a file | Finds it in the highest layer that has it. No copy is made |
| Creates a new file | Writes it into the container layer |
| Changes a file from the image | Copies the whole file up into the container layer first, then changes the copy |
| Deletes a file from the image | Puts a marker in the container layer that hides the file. The image keeps it |
The third row is copy-on-write. The image never changes, so every other container of that image still sees the original file.
Parts:
- Container web-1 (edits /opt/app/app.py)
- Layer of web-1 (changed copy of app.py)
- Image layer (app.py, read-only)
- Container web-2 (still reads the original)
Connections:
- Container web-1 to Layer of web-1: write
- Image layer to Layer of web-1: copy up
- Container web-2 to Image layer: read
You can see how little a container owns:
docker run -d --name web-1 my-app:1.0
docker run -d --name web-2 my-app:1.0
docker ps -s --format 'table {{.Names}}\t{{.Size}}'
NAMES SIZE
web-2 8.19kB (virtual 224MB)
web-1 12.3kB (virtual 224MB)
The first number is the container's own writable layer. The virtual size adds the image, but the image is on disk only once however many containers use it.
Why the container layer is the wrong place for data
The writable layer has three weaknesses:
- It is deleted with the container.
docker rmremoves the layer, and with it everything the application wrote. - It is tied to one container on one host. Another container cannot easily read it.
- It is slower. Every write passes through the storage driver, and the first change to a large file copies the whole file.
docker exec web-1 sh -c 'echo order-42 > /opt/app/orders.txt'
docker rm -f web-1
docker run -d --name web-1 my-app:1.0
docker exec web-1 cat /opt/app/orders.txt
cat: /opt/app/orders.txt: No such file or directory
A database that keeps its files in the container layer loses them on the first upgrade. This is the problem that mounts solve.
Volumes, bind mounts and tmpfs
A mount replaces one directory inside the container with storage that is not part of the layer stack. Writes to that directory skip the storage driver and go straight to the mounted storage.
Parts:
- Container (/var/lib/mysql)
- Volume (-v data:/var/lib/mysql)
- Bind mount (-v /srv/db:/var/lib/mysql)
- tmpfs mount (--tmpfs /run)
- /var/lib/docker/volumes (managed by Docker)
- Any host path (/srv/db, managed by you)
- Host memory (gone when it stops)
Connections:
- Container to Volume
- Container to Bind mount
- Container to tmpfs mount
- Volume to /var/lib/docker/volumes: stored in
- Bind mount to Any host path: points to
- tmpfs mount to Host memory: kept in
| Volume | Bind mount | tmpfs mount | |
|---|---|---|---|
| Where the data is | /var/lib/docker/volumes/NAME/_data | Any path on the host that you name | Host memory |
| Who manages it | Docker (docker volume ...) | You | Nobody |
Survives docker rm | Yes | Yes | No |
| Typical use | Database files, application data | Source code in development, host configuration files, host sockets | Scratch space, secrets that must not reach the disk |
| Short flag | -v data:/path | -v /host/path:/path | --tmpfs /path |
Volumes
docker volume create data_volume
docker run -d --name db -e MYSQL_ROOT_PASSWORD=pw \
-v data_volume:/var/lib/mysql mysql:8.4
MySQL now writes its database files to /var/lib/mysql, which is really
/var/lib/docker/volumes/data_volume/_data on the host. Remove the container and start a new one with the same
-v flag: the data is still there.
Three details are worth knowing:
- Docker creates a missing volume for you.
docker run -v data_volume2:/var/lib/mysql ...works withoutdocker volume create. - An empty volume is filled from the image. If the image already has files in the target directory, Docker copies them into a new, empty volume on first use. Bind mounts do not do this: they hide whatever the image had there.
- Anonymous volumes.
-v /var/lib/mysql, with no name, or aVOLUMEline in the Dockerfile, creates a volume with a random 64-character name. They are easy to forget and pile up on disk.
Bind mounts
docker run -d --name db -e MYSQL_ROOT_PASSWORD=pw \
-v /srv/db:/var/lib/mysql mysql:8.4
Here the data lives in /srv/db, a directory that you chose and that exists whether Docker is installed or not.
A bind mount gives the container direct access to the host's files, so it depends on the layout of that host and
it is a security decision: the container, often running as root, can change those files. Add :ro to make it
read-only.
The --mount flag
-v packs everything into one string separated by colons. --mount spells out each part as key=value:
docker run -d --name db -e MYSQL_ROOT_PASSWORD=pw \
--mount type=volume,source=data_volume,target=/var/lib/mysql mysql:8.4
docker run -d --name web \
--mount type=bind,source=/srv/site,target=/usr/share/nginx/html,readonly nginx:1.29-alpine
docker run -d --name cache \
--mount type=tmpfs,target=/cache,tmpfs-size=64m redis:8-alpine
| Key | Meaning |
|---|---|
type | volume, bind or tmpfs |
source or src | The volume name, or the host path |
target, destination or dst | The path inside the container |
readonly or ro | Mount read-only |
volume-driver, volume-opt | A volume driver and its options. See the next lesson |
Under the hood · What overlay2 looks like on disk
With the classic overlay2 driver, docker inspect shows the four directories that OverlayFS combines for a
container:
docker inspect -f '{{json .GraphDriver.Data}}' web-1 | jq
{
"LowerDir": "/var/lib/docker/overlay2/9d1f…-init/diff:/var/lib/docker/overlay2/4be0…/diff:/var/lib/docker/overlay2/71aa…/diff",
"MergedDir": "/var/lib/docker/overlay2/9d1f…/merged",
"UpperDir": "/var/lib/docker/overlay2/9d1f…/diff",
"WorkDir": "/var/lib/docker/overlay2/9d1f…/work"
}
- LowerDir is the list of read-only image layers, highest first.
- UpperDir is the container's writable layer. Files the container created or changed are plain files here.
- MergedDir is the union of both, and it is what the container sees as
/. - WorkDir is scratch space for OverlayFS itself.
So ls on the UpperDir as root on the host shows exactly what docker diff web-1 reports. A deleted image
file appears there as a character device with device number 0/0, called a whiteout.
With the containerd image store the same four roles exist, but the directories are snapshots under
/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots, and GraphDriver is not filled in.
From Docker to Kubernetes
Kubernetes nodes run containers through containerd, which stores images in the same layered way under
/var/lib/containerd. Everything above therefore holds for a Pod.
| Docker | Kubernetes |
|---|---|
| Image layers, shared and read-only | The same, managed by containerd on each node |
Writable container layer, lost on docker rm | Writable layer of each container, lost whenever the container restarts |
-v data:/path | A volumes entry in the Pod, plus volumeMounts in the container |
| Bind mount of a host path | A hostPath volume |
--tmpfs /path | An emptyDir volume with medium: Memory |
--mount ...,readonly | readOnly: true on the volumeMount |
| Volume on external storage through a driver | A PersistentVolume provided by a CSI driver |
Two differences matter:
- In Docker a restarted container keeps its writable layer until it is removed. In Kubernetes the kubelet creates a new container on every restart, so a crash already wipes the layer.
- What a container writes to its layer counts as ephemeral storage of the node. A Pod that writes too much there can be evicted.
The lesson Volumes shows the Kubernetes side in detail.
Using it
Example · Find out which storage driver a host uses
docker info --format '{{.Driver}}'
docker info | grep -A 3 'Storage Driver'
overlay2
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Using metacopy: false
On a fresh Docker Engine 29 host the first command prints overlayfs, and the details show
driver-type: io.containerd.snapshotter.v1. Both store layers with the kernel's OverlayFS.
Example · See what a container changed
docker run -d --name web-1 my-app:1.0
docker exec web-1 sh -c 'echo order-42 > /opt/app/orders.txt; echo "# patched" >> /opt/app/app.py; rm /etc/motd'
docker diff web-1
C /opt
C /opt/app
A /opt/app/orders.txt
C /opt/app/app.py
C /etc
D /etc/motd
A is added, C is changed and D is deleted. This is the content of the container layer. app.py was copied
up before it was changed, and the image still has the original.
Example · Keep a database across containers with a volume
docker run -d --name db -e MYSQL_ROOT_PASSWORD=pw \
--mount type=volume,source=data_volume,target=/var/lib/mysql mysql:8.4
docker exec db mysql -uroot -ppw -e 'CREATE DATABASE shop;'
docker rm -f db
docker run -d --name db2 -e MYSQL_ROOT_PASSWORD=pw \
--mount type=volume,source=data_volume,target=/var/lib/mysql mysql:8.4
docker exec db2 mysql -uroot -ppw -e 'SHOW DATABASES;' | grep shop
shop
The second container is a different container with a new writable layer, but the database files were never in that layer.
Example · Find where a container's data really is
docker inspect -f '{{range .Mounts}}{{.Type}} {{.Source}} -> {{.Destination}}{{"\n"}}{{end}}' db2
volume /var/lib/docker/volumes/data_volume/_data -> /var/lib/mysql
Mounts in docker inspect lists every volume, bind mount and tmpfs of a container. A directory that is not
listed there is in the container layer and will be lost.
Tricks
Common mistakes
- Storing data in the container layer. It works until the container is replaced, which happens on every upgrade.
- Confusing storage drivers with volume drivers. A storage driver (overlay2, a containerd snapshotter)
manages image and container layers. A volume driver (
local, or a plugin) manages volumes. They are unrelated settings. - Thinking each container has its own copy of the image. Ten containers of a 224 MB image use 224 MB plus ten small layers.
- A typing mistake in a bind mount path with
-v. Docker creates the wrong directory and the container starts with an empty mount. - Expecting a bind mount to be filled from the image. Only a new, empty volume is populated. A bind mount hides the image's files in that directory.
- Deleting files in a later layer to make an image smaller. The files stay in the earlier layer. Remove them
in the same
RUNinstruction that created them.
Recap
- An image is a stack of read-only layers. Containers of the same image share them.
- Each container adds one thin read-write layer. Changing an image file copies it up first: copy-on-write.
- The container layer is deleted with the container, so it is not a place for data.
- A volume (managed by Docker under
/var/lib/docker/volumes) or a bind mount (any host path) keeps data outside the layers. A tmpfs mount keeps it in memory only. -vis the short spelling and--mount type=...,source=...,target=...the explicit one. Kubernetes expresses the same thing withvolumesandvolumeMounts.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.