Skip to main content

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

Bash
docker volume create postgres-data
docker run -d --name postgres -v postgres-data:/var/lib/postgresql/data \
-e POSTGRES_PASSWORD=devpassword postgres:16
docker volume ls
docker volume inspect postgres-data
docker volume rm postgres-data # permanent deletion
docker volume prune # remove unused volumes
YAML
services:
postgres:
image: postgres:16-alpine
volumes:
- postgres-data:/var/lib/postgresql/data
volumes:
postgres-data:

Back up and restore

Bash
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-restored
docker run --rm -v postgres-data-restored:/target -v "$(pwd)":/backup:ro alpine \
tar xzf /backup/postgres-backup.tar.gz -C /target

For live databases, prefer the database's own dump or snapshot tool for consistent backups.

Tip

Always name volumes. Anonymous volumes get random IDs and are hard to track and back up.

Common Mistake

Assuming 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.

Found a mistake, an outdated step or a broken link?