MongoDB in Docker Compose
Running MongoDB using Docker makes it effortless, and it's even easier to run and manage MongoDB when using Docker Compose.
Follow these steps to run MongoDB with Docker Compose:
- Add the service below to a Compose file:
docker-compose.yml
services:
mongodb:
image: mongo:7
volumes:
- ./mounted_data/mongodb:/data/db
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: root
MONGO_INITDB_DATABASE: app
ports:
- "127.0.0.1:27017:27017"
restart: always
- Create the directory on the host where MongoDB data will be retained
mkdir -p mounted_data/mongodb
- Start the service
docker compose up -d mongodb
- Use the following connection string to connect to the database:
mongodb://root:root@localhost:27017
(If you're connecting from another container in the same Compose file, use mongodb as the hostname instead of localhost)
tip
The service is exposed only to the host machine, so you'll need to SSH into the host to connect from outside the host machine. For example, when using MongoDB Compass, etc.
info
Only a root user is created by default. You should create a new user with limited privileges if needed.