Skip to content
LF Cert Trainer

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

1/11Storage in Docker
0:00 / 4:15

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.

DirectoryWhat is in it
/var/lib/docker/volumesOne folder per volume, with the data under _data
/var/lib/docker/containersPer container: configuration, the log file, hostname, resolv.conf
/var/lib/docker/overlay2Image layers and container layers, with the classic overlay2 storage driver
/var/lib/docker/imageThe index that says which layers form which image
/var/lib/containerdImage 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.04 reuses the 78 MB base layer. It is stored once and pulled once.
  • Build cache. If you change only app.py, Docker rebuilds only the COPY layer 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.
An image is a stack of layers, a container adds one moreImage: read-only, sharedthenthenon topmergedusesLayer 3: app codeCOPY app.py, 1 kBLayer 2: packagesRUN apt-get, 146 MBLayer 1: base OSFROM ubuntu, 78 MBContainer layerread-write, one per containerMerged viewone file systemProcessreads and writes /
An image is a stack of layers, a container adds one more. Each Dockerfile instruction that changes files adds a read-only layer. A container gets one thin writable layer on top, and a storage driver merges the stack into the single file system the process sees.

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 fileFinds it in the highest layer that has it. No copy is made
Creates a new fileWrites it into the container layer
Changes a file from the imageCopies the whole file up into the container layer first, then changes the copy
Deletes a file from the imagePuts 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.

Copy-on-write: change a file from the imagewritecopy upreadContainer web-1edits /opt/app/app.pyLayer of web-1changed copy of app.pyImage layerapp.py, read-onlyContainer web-2still reads the original
Copy-on-write: change a file from the image. The image layer is never changed. The first write copies the file up into the container's own layer, and only that container sees the new version.

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 rm removes 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.

Three ways to store data outside the container layerstored inpoints tokept inContainer/var/lib/mysqlVolume-v data:/var/lib/mysqlBind mount-v /srv/db:/var/lib/mysqltmpfs mount--tmpfs /run/var/lib/docker/volumesmanaged by DockerAny host path/srv/db, managed by youHost memorygone when it stops
Three ways to store data outside the container layer. A mount replaces one directory of the container with storage that lives somewhere else. Only volumes and bind mounts survive the container.

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
VolumeBind mounttmpfs mount
Where the data is/var/lib/docker/volumes/NAME/_dataAny path on the host that you nameHost memory
Who manages itDocker (docker volume ...)YouNobody
Survives docker rmYesYesNo
Typical useDatabase files, application dataSource code in development, host configuration files, host socketsScratch 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 without docker 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 a VOLUME line 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
KeyMeaning
typevolume, bind or tmpfs
source or srcThe volume name, or the host path
target, destination or dstThe path inside the container
readonly or roMount read-only
volume-driver, volume-optA 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.

DockerKubernetes
Image layers, shared and read-onlyThe same, managed by containerd on each node
Writable container layer, lost on docker rmWritable layer of each container, lost whenever the container restarts
-v data:/pathA volumes entry in the Pod, plus volumeMounts in the container
Bind mount of a host pathA hostPath volume
--tmpfs /pathAn emptyDir volume with medium: Memory
--mount ...,readonlyreadOnly: true on the volumeMount
Volume on external storage through a driverA 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 RUN instruction 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.
  • -v is the short spelling and --mount type=...,source=...,target=... the explicit one. Kubernetes expresses the same thing with volumes and volumeMounts.

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.