Below is a clean, practical guide for running MongoDB in Docker—including the basic setup, volumes, authentication, networking, and common troubleshooting tips. Everything is written for beginners and production-minded users.
1. Prerequisites
Make sure you have:
Docker installed
(Optional) Docker Compose installed
Terminal access
You do not need MongoDB installed locally—Docker will handle it.
2. Run MongoDB in a Single Command
The easiest way:
docker run -d \
--name mongodb \
-p 27017:27017 \
mongo:latest
This:
Pulls the official MongoDB image
Runs a container in the background
Exposes the default MongoDB port 27017
No authentication (good for testing only)
Connect with a tool like Compass or from your app using:
mongodb://localhost:27017
3. Running MongoDB With a Persistent Volume
Without a volume, your data disappears when the container stops.
Create a named volume:
docker volume create mongo_data
Run MongoDB with persistence:
docker run -d \
--name mongodb \
-p 27017:27017 \
-v mongo_data:/data/db \
mongo:latest
Docker now stores MongoDB files in the mongo_data volume permanently.
4. Run MongoDB With Authentication (Recommended)
MongoDB official image lets you define a root user:
docker run -d \
--name mongodb \
-p 27017:27017 \
-v mongo_data:/data/db \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=secret123 \
mongo:latest
Your connection string becomes:
mongodb://admin:secret123@localhost:27017
5. Full Setup Using Docker Compose
Create a file named docker-compose.yml:
version: "3.8"
services:
mongodb:
image: mongo:latest
container_name: mongodb
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: secret123
volumes:
- mongo_data:/data/db
volumes:
mongo_data:
Start the stack:
docker compose up -d
Stop:
docker compose down
Remove containers but keep data:
docker compose down --volumes
6. Creating Additional Databases and Users Automatically
You can add initialization scripts inside /docker-entrypoint-initdb.d/.
Example: create init.js:
db.createUser({
user: "appUser",
pwd: "appPassword",
roles: [{ role: "readWrite", db: "mydb" }]
});
Place the file next to your docker-compose.yml and update your service:
volumes:
- mongo_data:/data/db
- ./init.js:/docker-entrypoint-initdb.d/init.js:ro
MongoDB will run the script only on first startup (when database is empty).
7. Connect From a Local Application
Node.js example:
const { MongoClient } = require("mongodb");
const uri = "mongodb://admin:secret123@localhost:27017";
(async () => {
const client = new MongoClient(uri);
await client.connect();
console.log("Connected to MongoDB!");
})();
Python example:
from pymongo import MongoClient
client = MongoClient("mongodb://admin:secret123@localhost:27017")
db = client.test
print(db.list_collection_names())
8. Running a MongoDB Replica Set in Docker (for Transactions or Change Streams)
Replica sets are required for advanced features.
A minimal replica set using Docker Compose:
version: "3.8"
services:
mongo1:
image: mongo
ports: ["27017:27017"]
command: ["mongod", "--replSet", "rs0"]
volumes:
- mongo1:/data/db
mongo2:
image: mongo
ports: ["27018:27017"]
command: ["mongod", "--replSet", "rs0"]
volumes:
- mongo2:/data/db
mongo3:
image: mongo
ports: ["27019:27017"]
command: ["mongod", "--replSet", "rs0"]
volumes:
- mongo3:/data/db
volumes:
mongo1:
mongo2:
mongo3:
Then initialize:
docker exec -it mongo1 mongosh --eval "
rs.initiate({
_id: 'rs0',
members: [
{ _id: 0, host: 'mongo1:27017' },
{ _id: 1, host: 'mongo2:27017' },
{ _id: 2, host: 'mongo3:27017' }
]
})
"
9. Useful Docker Commands
View logs:
docker logs mongodb
Enter the Mongo shell:
docker exec -it mongodb mongosh
Stop and remove container:
docker rm -f mongodb
List volumes:
docker volume ls
10. Common Troubleshooting
❗ “MongoDB connection refused”
Container may not be running: docker ps
Port conflict: ensure no local MongoDB is running
Authentication mismatch: verify username/password
❗ “Data missing after restart”
Ensure you mounted a volume
Without -v mongo_data:/data/db, MongoDB uses ephemeral storage
❗ “Permission denied on volumes”
On Linux, you may need to adjust file permissions:
sudo chown -R 999:999 /var/lib/docker/volumes/mongo_data
✔ Final Summary
Goal Command / Solution
Run MongoDB quickly docker run -d -p 27017:27017 mongo
Run with persistence Add -v mongo_data:/data/db
Run with username/password Add MONGO_INITDB_ROOT_USERNAME env vars
Use Compose Build a docker-compose.yml file
Advanced features Use replica sets
Initialize database Add scripts to /docker-entrypoint-initdb.d
Learn MERN Stack Training in Hyderabad
Read More
Using PM2 for Node Process Management
Setting up NGINX for a MERN App
Continuous Deployment with Vercel & Heroku
Visit Our Quality Thought Training Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments