Why Volumes?
Container filesystems are ephemeral — when a container is removed, its data is lost. Docker volumes provide persistent storage that survives container restarts and removals.
Volume Types
| Type | Syntax | Use Case |
|---|---|---|
| Named volume | -v mydata:/data | Database files, application data |
| Bind mount | -v /host/path:/container/path | Development, config files |
| tmpfs | --tmpfs /tmp | Temporary files, secrets |
Managing Volumes
# Create a named volume
docker volume create myapp-data
# List all volumes
docker volume ls
# Inspect a volume
docker volume inspect myapp-data
# Remove a volume
docker volume rm myapp-data
# Remove all unused volumes
docker volume pruneUsing Volumes in Compose
services:
postgres:
image: postgres:16
volumes:
- pg-data:/var/lib/postgresql/data
app:
build: .
volumes:
- ./src:/app/src # Bind mount for development
- app-uploads:/app/uploads # Named volume for user uploads
volumes:
pg-data:
app-uploads:Backup and Restore
# Backup a volume to a tar file
docker run --rm -v myapp-data:/data -v $(pwd):/backup alpine tar czf /backup/myapp-data.tar.gz -C /data .
# Restore from backup
docker run --rm -v myapp-data:/data -v $(pwd):/backup alpine sh -c "cd /data && tar xzf /backup/myapp-data.tar.gz"Volume Drivers
Docker supports remote volume drivers for NFS, cloud storage, and distributed filesystems:
# NFS volume
docker volume create --driver local \
--opt type=nfs \
--opt o=addr=192.168.1.100,rw \
--opt device=:/exported/path \
nfs-data