Let's now look at using Docker Volumes when working with Docker Compose. We will use the same Node.js application example.
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.
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/According to MongoDB documentation:
/data/dbThis is the container directory path where MongoDB stores its data.
We map it to our host machine directory:
/Users/your-username/Desktop/dataSo now:
Host Machine ↔ MongoDB Container Storage/Desktop/data (Host Machine)
↕
/data/db (Mongo Container)docker compose -f mongodb.yaml up -d/data/dbAfter running the command:
/Desktop/dataYou will see files automatically created by MongoDB.
This confirms:
Visit:
http://localhost:8081Then:
college-dbusersExample:
{
"email": "john@yahoo.in",
"username": "JohnDoe",
"password": "secret"
}docker compose -f mongodb.yaml downThis will:
But ❗ data remains intact
docker compose -f mongodb.yaml up -dVisit:
http://localhost:8081Now you will see:
college-db still existsusers collection still existsEven after:
The data is still available.
Because data is stored outside the container in a Docker Volume (bind mount):
Container → /data/db → Host Machine FolderSo the container can be destroyed, but the data remains safe.
Docker Volumes make databases persistent and production-ready.
Without volumes:
With volumes:
/data/dbdocker compose down