Volumes, Bind Mounts and Persistence
Pick storage by lifetime and ownership: the writable layer is disposable, volumes are Docker-managed durable data, bind mounts expose host paths, and tmpfs is memory-only scratch space.
Key points
- 1
The writable layer survives
docker stopbut is deleted bydocker rm; it uses copy-on-write, so large or write-heavy files belong in a volume. - 2
A bare name in
-v name:/pathis a named volume; an absolute path is a bind mount.-vcreates missing host paths as root-owned directories, while--mount type=bindfails instead. - 3
An empty volume mounted over a non-empty image directory is pre-populated from the image, keeping ownership. Bind mounts never copy; they hide the image's content.
- 4
Images with
VOLUMEcreate a new anonymous volume per container.--rmanddocker rm -vdelete anonymous volumes; named volumes are only removed explicitly. - 5
Since Engine 23,
docker volume pruneremoves only unused anonymous volumes;--alladds named ones, anddocker system pruneneeds--volumesto touch volumes at all. - 6
Bind-mount permissions are the host's: match UIDs with
--userorchown, remember userns-remap shifts UIDs, and use:z/:Zon SELinux hosts. - 7
tmpfs is Linux-only, private to one container, unlimited in size by default (mode 1777), and gone when the container stops.
Common traps
A named volume that already holds data is never refreshed from a new image, so stale
node_modulesor assets can shadow the new ones.Bind-mounting a single file pins its inode: editors that save by renaming leave the container reading the old file.
Copying a live database's files (tar on a running container) can produce a backup that won't restore; use the engine's backup tools or stop writes.
Read the source
Test yourself on Volumes, Bind Mounts and Persistence
Ten questions, with the answer and explanation after each one.