Docker Volume
A Docker volume is Docker-managed persistent storage that lives outside a container's writable layer. Data in a volume survives container removal and can be shared between containers.
Why volumes exist
Everything a container writes to its own filesystem is deleted with the container. A volume stores data under Docker's storage area (on Linux, /var/lib/docker/volumes/<name>/_data) and attaches it at a path inside the container. Volumes also bypass the union filesystem, which gives native I/O speed for databases.
Volume, bind mount, or tmpfs
| Type | Source | Best for |
|---|---|---|
| Named volume | Managed by Docker | Production data such as databases |
| Bind mount | A host path you choose | Development code, config files |
| tmpfs | Memory only | Scratch data and temporary secrets |
Working with volumes
docker volume create postgres-datadocker run -d --name postgres -v postgres-data:/var/lib/postgresql/data \ -e POSTGRES_PASSWORD=devpassword postgres:16docker volume lsdocker volume inspect postgres-datadocker volume rm postgres-data # permanent deletiondocker volume prune # remove unused volumesservices: postgres: image: postgres:16-alpine volumes: - postgres-data:/var/lib/postgresql/data volumes: postgres-data:Back up and restore
docker run --rm -v postgres-data:/source:ro -v "$(pwd)":/backup alpine \ tar czf /backup/postgres-backup.tar.gz -C /source . docker volume create postgres-data-restoreddocker run --rm -v postgres-data-restored:/target -v "$(pwd)":/backup:ro alpine \ tar xzf /backup/postgres-backup.tar.gz -C /targetFor live databases, prefer the database's own dump or snapshot tool for consistent backups.
TipAlways name volumes. Anonymous volumes get random IDs and are hard to track and back up.
Common MistakeAssuming a volume is a backup. It survives restarts, but not
docker volume rm, careless prunes, or host failure.
Frequently Asked Questions
Why use a named volume instead of a bind mount?
A named volume is managed by Docker, portable across hosts, and does not depend on a host path or its permissions. Bind mounts suit development, where you want live host files inside the container.
Does a volume protect data from loss?
It protects against container removal, not against deletion, prune commands, or disk failure. Schedule backups or use replication for important data.
Where is volume data stored?
On Linux under /var/lib/docker/volumes by default, though volume drivers can place data on network or cloud storage.