
Running MongoDB in Docker: A Practical Guide for Backend Developers
How to run MongoDB locally using Docker and Docker Compose, connect it to a Node.js app, and manage data with persistent volumes — no local MongoDB install needed.
Why Docker for MongoDB?
Installing MongoDB locally clutters your system. When you use Docker, you get a clean, isolated instance you can start and stop on demand — and share the same docker-compose.yml across your team.
Quickstart: MongoDB in Docker
docker run -d \
--name mongodb \
-p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=secret \
mongo:7That's it. MongoDB is now running at localhost:27017.
Using Docker Compose (Recommended)
For projects, always use Compose so you can version-control the setup:
# docker-compose.yml
version: '3.8'
services:
mongodb:
image: mongo:7
container_name: mongodb
restart: unless-stopped
ports:
- '27017:27017'
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: secret
volumes:
- mongo_data:/data/db
volumes:
mongo_data:docker-compose up -dThe mongo_data volume means your data persists across container restarts.
Connecting from Node.js
import mongoose from 'mongoose';
const MONGO_URI = 'mongodb://admin:secret@localhost:27017/myapp?authSource=admin';
await mongoose.connect(MONGO_URI);
console.log('Connected to MongoDB');Store credentials in .env, never hardcoded:
MONGO_URI=mongodb://admin:secret@localhost:27017/myapp?authSource=admin
Useful Commands
# View logs
docker logs mongodb
# Open MongoDB shell
docker exec -it mongodb mongosh -u admin -p secret
# Stop and remove container
docker-compose down
# Remove container AND volume (wipes data)
docker-compose down -vCommon Issues
| Problem | Fix |
|---|---|
| Authentication failed | Include ?authSource=admin in URI |
| Port already in use | Change host port to 27018:27017 |
| Data lost on restart | Use a named volume (see Compose above) |
| Container won't start | Run docker logs mongodb to debug |
What I Learned
- Docker volumes are the difference between a toy setup and a real one.
- The
authSource=adminparameter is almost always needed when auth is enabled. - Keeping MongoDB in Docker makes onboarding new devs effortless — one command and they're running.
Read the Full Article
This article is hosted on Hashnode. Read it here →


