Docker Volumes with Docker Compose
Let's now look at using Docker Volumes when working with Docker Compose. We will use the same Node.js application example.
Problem We Had Earlier
We noticed earlier that when we stop and restart our MongoDB container, all data in the MongoDB database is lost.
To solve this, we will now add Docker Volumes to our mongodb.yaml file to bring persistence.
Updated Docker Compose File
version: '3.8'
services:
mongo:
image: mongo
ports:
- 27017:27017
volumes:
- /Users/your-username/Desktop/data:/data/db
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: qwerty
mongo-express:
image: mongo-express
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: admin
ME_CONFIG_MONGODB_ADMINPASSWORD: qwerty
ME_CONFIG_MONGODB_URL: mongodb://admin:qwerty@mongo:27017/
Important Concept — MongoDB Data Directory
According to MongoDB documentation:
This is the container directory path where MongoDB stores its data.
We map it to our host machine directory:
/Users/your-username/Desktop/data
So now:
Host Machine ↔ MongoDB Container Storage
How Volume Mapping Works
/Desktop/data (Host Machine)
↕
/data/db (Mongo Container)
Running Docker Compose
docker compose -f mongodb.yaml up -d
What Happens Internally?
- Docker creates containers
- Docker mounts the host directory to
/data/db
- MongoDB starts using this mapped storage
- Any data written is stored on the host machine
Verifying Volume Setup
After running the command:
- Check your Desktop folder
You will see files automatically created by MongoDB.
This confirms:
- Volume is successfully mounted
- Data is being persisted outside the container
Testing Persistence
Step 1 — Open Mongo Express
Visit:
Then:
- Create database →
college-db
- Create collection →
users
- Add a document
Example:
{
"email": "john@yahoo.in",
"username": "JohnDoe",
"password": "secret"
}
Step 2 — Stop and Remove Containers
docker compose -f mongodb.yaml down
This will:
- Stop all containers
- Remove containers
- Remove Docker network
But ❗ data remains intact
Step 3 — Restart Containers
docker compose -f mongodb.yaml up -d
Step 4 — Verify Data Again
Visit:
Now you will see:
college-db still exists
users collection still exists
- Previously added document is still present
Final Result
Even after:
- Stopping containers
- Removing containers
- Recreating containers
The data is still available.
Why This Works
Because data is stored outside the container in a Docker Volume (bind mount):
Container → /data/db → Host Machine Folder
So the container can be destroyed, but the data remains safe.
Key Takeaway
Docker Volumes make databases persistent and production-ready.
Without volumes:
With volumes:
- Data survives restarts and deletions ✅
Summary
- MongoDB stores data in
/data/db
- We map it to a host directory using volumes
- Docker Compose supports volumes directly
- Data persists even after
docker compose down
- This is essential for real-world database applications