What are Docker Volumes?
By default, data inside a Docker container is lost when the container stops or is deleted. Docker Volumes solve this problem by providing a way to persist data outside the container lifecycle.
Volumes are managed by Docker and stored on the host filesystem.
Types of Docker Storage
| Type | Description |
|---|---|
| Volume | Managed by Docker, stored in /var/lib/docker/volumes/ |
| Bind Mount | Maps a specific host path to a container path |
| tmpfs Mount | Stored in host memory only (not persisted) |
Volume Commands
| Command | Description |
|---|---|
docker volume create <name> | Create a named volume |
docker volume ls | List all volumes |
docker volume inspect <name> | Inspect volume details |
docker volume rm <name> | Remove a volume |
docker volume prune | Remove all unused volumes |
Example 1: Create and Use a Volume
# Create a named volume
docker volume create my-data
# Run a container with the volume mounted
docker run -d --name my-container -v my-data:/app/data ubuntu
Any data written to /app/data inside the container will be saved in the my-data volume.
Example 2: Bind Mount (Map Host Folder)
# Map current host folder to container /var/www/html
docker run -d --name my-nginx -p 8080:80 -v $(pwd)/html:/usr/share/nginx/html nginx
Changes to files in your local html folder are immediately reflected inside the container.
Example 3: MySQL with Persistent Volume
docker run -d --name mysql-db -e MYSQL_ROOT_PASSWORD=secret -e MYSQL_DATABASE=mydb -v mysql-data:/var/lib/mysql mysql:8.0
MySQL data is now persisted in the mysql-data volume even if the container is deleted.
Example 4: Inspect a Volume
docker volume inspect mysql-data
Output:
[
{
"Name": "mysql-data",
"Driver": "local",
"Mountpoint": "/var/lib/docker/volumes/mysql-data/_data"
}
]Volume vs Bind Mount
| Feature | Volume | Bind Mount |
|---|---|---|
| Managed by | Docker | You (host path) |
| Best for | Production data persistence | Development (live reload) |
| Performance | Better on Linux | Can be slower on Mac/Win |
| Portability | Portable across hosts | Host-dependent |
Summary
- Docker volumes persist data beyond the container lifecycle.
- Use named volumes for production data (MySQL, uploads, etc.).
- Use bind mounts during development for live code reloading.
- Clean up unused volumes with
docker volume prune.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
