
Master MongoDB containerization with this comprehensive guide covering Docker setup, Docker Compose configurations, security best practices, and production deployment strategies.
Setting up MongoDB in a containerized environment offers flexibility, scalability, and consistency across different environments. This comprehensive guide will walk you through setting up MongoDB using both Docker and Docker Compose, with production-ready configurations.
Table of Contents
Prerequisites
Before starting, ensure you have:
- Docker Engine installed (version 20.10 or later)
- Docker Compose installed (version 2.0 or later)
- Basic understanding of MongoDB concepts
- Terminal access with administrative privileges
Basic Docker Setup
1. Simple MongoDB Container
# Pull the official MongoDB image
docker pull mongodb/mongodb-community-server:6.0-ubi8
# Run a basic MongoDB container
docker run --name mongodb \
-d \
-p 27017:27017 \
mongodb/mongodb-community-server:6.0-ubi82. Container with Authentication
# Run MongoDB with authentication
docker run --name mongodb-secure \
-d \
-p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=secretpassword \
mongodb/mongodb-community-server:6.0-ubi83. Persistent Storage
# Create a Docker volume
docker volume create mongodb_data
# Run MongoDB with persistent storage
docker run --name mongodb-persistent \
-d \
-p 27017:27017 \
-v mongodb_data:/data/db \
mongodb/mongodb-community-server:6.0-ubi8Docker Compose Configuration
1. Basic Docker Compose Setup
# docker-compose.yml
version: '3.8'
services:
mongodb:
image: mongodb/mongodb-community-server:6.0-ubi8
container_name: mongodb
ports:
- "27017:27017"
volumes:
- mongodb_data:/data/db
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=secretpassword
volumes:
mongodb_data:2. MongoDB with Replica Set
# docker-compose-replica.yml
version: '3.8'
services:
mongodb-primary:
image: mongodb/mongodb-community-server:6.0-ubi8
container_name: mongodb-primary
command: ["--replSet", "rs0", "--bind_ip_all"]
ports:
- "27017:27017"
volumes:
- mongodb_primary:/data/db
networks:
- mongodb_network
mongodb-secondary1:
image: mongodb/mongodb-community-server:6.0-ubi8
container_name: mongodb-secondary1
command: ["--replSet", "rs0", "--bind_ip_all"]
volumes:
- mongodb_secondary1:/data/db
networks:
- mongodb_network
mongodb-secondary2:
image: mongodb/mongodb-community-server:6.0-ubi8
container_name: mongodb-secondary2
command: ["--replSet", "rs0", "--bind_ip_all"]
volumes:
- mongodb_secondary2:/data/db
networks:
- mongodb_network
volumes:
mongodb_primary:
mongodb_secondary1:
mongodb_secondary2:
networks:
mongodb_network:
driver: bridge3. Initialize Replica Set
// init-replica.js
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "mongodb-primary:27017" },
{ _id: 1, host: "mongodb-secondary1:27017" },
{ _id: 2, host: "mongodb-secondary2:27017" }
]
})Security Best Practices
1. Custom MongoDB Configuration
# mongod.conf
security:
authorization: enabled
javascriptEnabled: false
net:
bindIp: 0.0.0.0
port: 27017
ssl:
mode: requireSSL
PEMKeyFile: /etc/ssl/mongodb.pem
storage:
dbPath: /data/db
journal:
enabled: true
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true2. Secure Docker Compose Configuration
# docker-compose-secure.yml
version: '3.8'
services:
mongodb:
image: mongodb/mongodb-community-server:6.0-ubi8
container_name: mongodb-secure
ports:
- "27017:27017"
volumes:
- mongodb_data:/data/db
- ./mongod.conf:/etc/mongod.conf
- ./ssl:/etc/ssl
- ./logs:/var/log/mongodb
environment:
- MONGO_INITDB_ROOT_USERNAME_FILE=/run/secrets/mongo_root_username
- MONGO_INITDB_ROOT_PASSWORD_FILE=/run/secrets/mongo_root_password
command: ["--config", "/etc/mongod.conf"]
secrets:
- mongo_root_username
- mongo_root_password
ulimits:
nproc: 64000
nofile:
soft: 64000
hard: 64000
volumes:
mongodb_data:
secrets:
mongo_root_username:
file: ./secrets/root_username.txt
mongo_root_password:
file: ./secrets/root_password.txtProduction Deployment
1. Resource Limits
# docker-compose-production.yml
services:
mongodb:
deploy:
resources:
limits:
cpus: '2'
memory: 4G
reservations:
cpus: '1'
memory: 2G2. Monitoring Setup
# docker-compose-monitoring.yml
services:
mongodb:
# ... existing configuration ...
mongodb-exporter:
image: percona/mongodb_exporter:0.20
container_name: mongodb-exporter
command:
- '--mongodb.uri=mongodb://admin:password@mongodb:27017'
ports:
- "9216:9216"
depends_on:
- mongodbAdvanced Configurations
1. Sharded Cluster Setup
# docker-compose-sharded.yml
version: '3.8'
services:
configserver1:
image: mongodb/mongodb-community-server:6.0-ubi8
command: ["--configsvr", "--replSet", "configReplSet"]
volumes:
- configserver1:/data/db
networks:
- mongodb_network
shard1-1:
image: mongodb/mongodb-community-server:6.0-ubi8
command: ["--shardsvr", "--replSet", "shard1ReplSet"]
volumes:
- shard1-1:/data/db
networks:
- mongodb_network
mongos:
image: mongodb/mongodb-community-server:6.0-ubi8
command: "mongos --configdb configReplSet/configserver1:27017"
ports:
- "27017:27017"
networks:
- mongodb_network
depends_on:
- configserver1
- shard1-1
volumes:
configserver1:
shard1-1:
networks:
mongodb_network:
driver: bridge2. Backup Configuration
# docker-compose-backup.yml
services:
mongodb:
# ... existing configuration ...
mongodb-backup:
image: mongo:6.0
volumes:
- ./backups:/backups
entrypoint: ["/bin/bash", "-c"]
command:
- |
while true; do
mongodump --uri="mongodb://admin:password@mongodb:27017" --out="/backups/$(date +%Y%m%d)"
sleep 86400
done
depends_on:
- mongodbTroubleshooting
Common Issues and Solutions
- Container fails to start:
# Check container logs
docker logs mongodb
# Check MongoDB logs
docker exec mongodb cat /var/log/mongodb/mongod.log- Connection issues:
# Test network connectivity
docker exec mongodb mongosh --eval "db.runCommand({ping: 1})"
# Check container networking
docker network inspect mongodb_network- Performance issues:
# Monitor container resources
docker stats mongodb
# Check MongoDB metrics
docker exec mongodb mongosh --eval "db.serverStatus()"Best Practices Summary
Security:
- Always enable authentication
- Use secrets management
- Implement network isolation
- Regular security audits
Performance:
- Set appropriate resource limits
- Monitor container metrics
- Use volume mounts for persistence
- Implement proper indexing
Maintenance:
- Regular backups
- Monitor logs
- Update container images
- Health checks
Conclusion
Setting up MongoDB with Docker and Docker Compose provides a flexible and scalable database environment. By following this guide's best practices and security recommendations, you can create a robust, production-ready MongoDB deployment.
Remember to:
- Regularly update MongoDB and Docker images
- Monitor container and database performance
- Implement proper backup strategies
- Follow security best practices
Additional Resources
Written by
TheDBAdmin Team
KEEP LEARNING WITH THEDBADMIN
Turn this guide into a skill you can prove
Keep reading
Related articles
NextGen DBA + AI Engineer Bootcamp
Instructor-led, lab-first training for production DBAs: PostgreSQL, MongoDB, Docker, Kubernetes and AI.
- Live labs on real execution plans
- Backup, PITR & HA in production
- pgvector, RAG & AI for DBAs
🛒 FROM THE SHOP

PostgreSQL Observability Pipeline with Prometheus, Grafana, and Alloy
PDF · 10 pages
Free