Introduction to Volumes
Volumes are Docker-managed storage that persists data even after a container is removed.
docker run -v VOLUME_NAME:/path/in/container IMAGEBy default, anything a container writes lives in its writable layer and disappears when the container is deleted. To keep data, use a volume.
What is a volume?
A volume is storage managed by Docker, stored outside any single container. Multiple containers can share it, and it survives container removal.
Why prefer volumes
- Data persists across container restarts and rebuilds.
- Docker manages the location, so it is portable.
- Better performance than bind mounts on Docker Desktop.
Mount a volume with the -v or --mount flag, giving a volume name and a path inside the container.
Example
# Create a named volume and use it for Postgres data
docker volume create pgdata
docker run -d \
-v pgdata:/var/lib/postgresql/data \
-e POSTGRES_PASSWORD=secret \
--name db postgres:16
# The data survives even if you remove and recreate the container
docker rm -f dbWhen to use it
- A team mounts a named volume to a PostgreSQL container so database data persists across container upgrades and restarts.
- A DevOps engineer backs up application uploads by copying the contents of a named volume to an S3 bucket each night.
- Two containers share a named volume so a file-processing worker can read files written by the web container.
More examples
Create and mount a named volume
Creates a Docker-managed volume and mounts it at the path where Postgres stores its data files.
# Create a named volume
docker volume create pgdata
# Mount it to a Postgres container
docker run -d \
--name db \
-v pgdata:/var/lib/postgresql/data \
postgres:16-alpineShare volume between two containers
Mounts the same named volume in two containers so they can exchange files through the shared directory.
docker volume create shared-uploads
docker run -d --name web \
-v shared-uploads:/app/uploads myapp:latest
docker run -d --name worker \
-v shared-uploads:/data/uploads myworker:latestBackup a volume to a tar archive
Spins up a temporary Alpine container to tar the volume contents into the current host directory.
docker run --rm \
-v pgdata:/data \
-v $(pwd):/backup \
alpine \
tar czf /backup/pgdata-backup.tar.gz -C /data .
Discussion