MongoDB is one of the most popular NoSQL databases, and running it inside a Docker container makes it lightweight, isolated, and portable. In this post, weโll walk through how to set up MongoDB with Docker, persist your data, and access it both from your application containers and directly from your host machine (OS) using tools like MongoDB Compass.
๐น Why Use Docker for MongoDB?
Isolation: MongoDB runs in a container, independent of your OS setup.
Portability: Same configuration runs on any machine with Docker.
Persistence: Store data in Docker volumes so it survives container restarts.
Networking: Easy communication between your app and MongoDB using Docker networks.
๐ Step 1: Run MongoDB in Docker
Weโll start with a simple docker run
command:
docker run -d \
--name mongo \
-p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=root \
-e MONGO_INITDB_ROOT_PASSWORD=example \
-v mongo-data:/data/db \
mongo:7
Explanation:
-d
โ run in detached mode--name mongo
โ name the containermongo
-p 27017:27017
โ map container port 27017 to host port 27017-e MONGO_INITDB_ROOT_USERNAME=root
โ admin username-e MONGO_INITDB_ROOT_PASSWORD=example
โ admin password-v mongo-data:/data/db
โ persistent storage for MongoDB datamongo:7
โ official MongoDB v7 image
Now you have MongoDB running in Docker ๐
๐ Step 2: Verify MongoDB Is Running
Run:
docker ps
You should see your mongo
container up and exposing port 27017
.
๐ Step 3: Access MongoDB from Your OS
Since we mapped port 27017
, you can connect using localhost from your machine.
Using MongoDB Compass:
Open Compass.
-
Enter the connection string:
mongodb://root:example@localhost:27017/mydatabase?authSource=admin
- `root:example` โ matches the username/password set in `docker run`
- `localhost:27017` โ because the port is exposed to your host
- `mydatabase` โ any database you want to connect to
- `authSource=admin` โ required since root user is created in the `admin` database
- Click Connect โ
๐ Step 4: Access MongoDB from CLI
You can also connect from your terminal using mongosh
(if installed):
mongosh "mongodb://root:example@localhost:27017/mydatabase?authSource=admin"
๐ Step 5: Access MongoDB from Another Container
If your application container needs to connect to MongoDB:
Use the container name (
mongo
) as hostname inside the Docker network.Example
.env
for your app:
MONGO_URL=mongodb://root:example@mongo:27017/mydatabase?authSource=admin
๐ Note:
mongo
works inside Docker network, but from your host OS, you must uselocalhost
.
๐ฏ Wrapping Up
Youโve just:
Run MongoDB in Docker with persistence.
Connected from your host OS using localhost.
Learned the difference between connecting from inside Docker vs. outside.
This approach is great for local development, prototyping, or even small deployments. For production, youโd likely want to configure authentication, backups, and monitoring.
Top comments (0)