Docker Volumes
Now we are going to cover the concept of Docker Volumes — a very interesting concept.
The Problem Without Volumes
In our previous example, when we built a Node.js application with MongoDB containers, we noticed something important:
All the data we added to the MongoDB database — such as:
- Creating the database
- Creating collections
- Adding documents
was not permanent.
Why Data Was Lost
By default, containers have a virtual file system.
- Data is stored inside the container filesystem
- When the container stops → data is gone
- When the container restarts → everything starts fresh
So:
Stop container → Data lost
Restart container → New clean state
What Are Docker Volumes?
Volumes in Docker are persistent data stores for containers.
They are used to store data outside the container so it does not get deleted when the container stops or is removed.
How Docker Volumes Work
The concept is simple:
- We reserve extra storage space on the host system
- This space is managed by Docker (in most cases)
- We mount this volume into a container
- The container starts using this external storage
Data Flow
Container ↔ Docker Volume ↔ Host System Storage
Key Idea
Whatever data is stored inside the container is also stored in the volume.
So:
- Container writes data → volume gets updated
- Container restarts → volume restores data
- Container is deleted → volume still has data
Why Volumes Are Important
Without volumes:
- Data is temporary
- Containers are stateless
- Restart = data loss
With volumes:
- Data becomes persistent
- Containers become state-aware
- Restart does not affect stored data
What Happens When Container Restarts?
If we restart a container:
- Docker does NOT delete the volume
- Container reconnects to the same volume
- Old data becomes available again
What Happens When Container Is Deleted?
Even if we delete the container:
The volume still exists.
So:
- Container removed ❌
- Data still available ✅
Sharing Data Between Containers
Volumes can also be shared between multiple containers.
For example:
- Mongo 1 container
- Mongo 2 container
Both can use the same volume.
Shared Volume Concept
Mongo Container 1 ─┐
├── Docker Volume ── Persistent Storage
Mongo Container 2 ─┘
Benefits of Docker Volumes
1. Data Persistence
Data is not lost when containers stop or restart.
2. Container Independence
Containers can be removed without losing data.
3. Data Sharing
Multiple containers can access the same stored data.
4. Backup Friendly
Data exists outside containers, making backup easier.
5. Production Ready
Volumes are essential for real-world applications like:
- Databases (MongoDB, MySQL, PostgreSQL)
- File storage systems
- Logging systems
Summary
- Containers are ephemeral (temporary) by default
- Data inside containers is lost when they stop
- Docker Volumes provide persistent storage
- Volumes exist outside the container lifecycle
- Data remains safe even if containers are deleted
- Multiple containers can share the same volume