Docker Volumes


The Problem: Ephemeral Containers
By default, Docker containers are ephemeral—meaning any data stored inside them is lost when the container stops or is removed. This is problematic for applications like databases, file storage, or any service requiring persistent data.
The Solution: Docker Volumes
Docker volumes provide a way to persist data by creating a virtual file system that can be mounted to the host machine. This ensures:
Data survives container restarts or removal
Automatic replication between container and host
Better performance and maintainability
Types of Docker Volumes
1. Host Volumes (Bind Mounts)
You manually specify the exact path on the host machine.
Useful when you need direct control over the storage location.
Example Command:
docker run --name postgres_db -e POSTGRES_PASSWORD=password \
-v /users/your_name/docker_volumes/postgres/data:/var/lib/postgres/data \
postgres
✅ Use Case: Development environments where you need to access files directly from the host.
2. Anonymous Volumes
Only the container path is specified (Docker auto-generates a random host directory).
Temporary storage—deleted when the container is removed unless manually preserved.
Example Command:
docker run --name postgres_db -e POSTGRES_PASSWORD=password \
-v /var/lib/postgres/data \
postgres
⚠ Limitation: Hard to manage since the host path is random.
3. Named Volumes (Recommended for Production)
You assign a name to the volume (Docker manages the host path internally).
Best for production—improves performance, maintainability, and backups.
Example Command:
docker run --name postgres_db -e POSTGRES_PASSWORD=password \
-v postgres_data:/var/lib/postgres/data \
postgres
Advantages:
Easier to reference (no need to know the host path).
Managed by Docker (automatically stored in
/var/lib/docker/volumes/
).Better for scaling and backups.
When to Use Each Volume Type?
Volume Type | Best For | Production-Ready? |
Host Volumes | Development, direct host access | ❌ (Manual management) |
Anonymous Volumes | Temporary data, testing | ❌ (Hard to track) |
Named Volumes | Databases, production workloads | ✅ (Docker-managed) |
Managing Docker Volumes
List All Volumes
docker volume ls
Inspect a Volume
docker volume inspect volume_name
Remove Unused Volumes
docker volume prune
Backup a Named Volume
docker run --rm -v postgres_data:/source -v /backup:/backup alpine \
tar cvf /backup/postgres_backup.tar /source
Key TakeAways
Use Host Volumes for development when you need direct file access.
Use Named Volumes for production databases and persistent storage.
Avoid Anonymous Volumes unless for temporary testing.
By using volumes correctly, you ensure data persistence, easier backups, and smoother container management.
Subscribe to my newsletter
Read articles from Phenny Mwaisaka directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by