Deploying MongoDB
Self-hosted MongoDB with Docker, replica sets, and sharding for horizontal scale.
PlatformsAdvanced
Why
Self-hosted MongoDB gives control over replica set topology, sharding, and storage engine (WiredTiger). With sharding, you scale horizontally across shards.
Platform-as-a-Service adoption grew 24% in 2024 as teams shift from VM management to git-push deploys. the cloud infrastructure market reached $330B in 2024, growing 22% year-over-year (Synergy Research), and PaaS layers capture the majority of new workloads.
When
Use self-hosted MongoDB for document workloads, sharding, and custom aggregation. Prefer Atlas for managed.
How
1. Docker — mongo:7 image with volume
2. Replica set — 3 nodes minimum for production HA
3. Init — rs.initiate() in mongosh
4. Sharding — sh.addShard() for horizontal scale
5. Auth — enable auth, create users
6. Backup — mongodump or mongosync for continuous
7. Monitoring — mongostat, mongotop, free monitoring
Example
# docker-compose.yml — replica set
services:
mongo1: { image: mongo:7, command: --replSet rs0, ports: ["27017:27017"] }
mongo2: { image: mongo:7, command: --replSet rs0 }
mongo3: { image: mongo:7, command: --replSet rs0 }
# Init replica set
docker exec mongo1 mongosh --eval '
rs.initiate({
members: [
{ _id: 0, host: "mongo1:27017" },
{ _id: 1, host: "mongo2:27017" },
{ _id: 2, host: "mongo3:27017" }
]
})'
# Connection string
mongodb://mongo1:27017,mongo2:27017,mongo3:27017/mydb?replicaSet=rs0
# Backup
mongodump --uri="mongodb://mongo1:27017" --out=/backup
Common Problems
- ⚠Single node no HA — development only, production needs 3-node replica set
- ⚠No auth enabled — anyone can connect, enable auth and create admin user
- ⚠Configuration drift between environments — use infrastructure-as-code (Terraform/Pulumi) to keep dev/staging/prod identical
Best Practices
- ✓Always use replica set (3 nodes) — HA, automatic failover, read scaling
- ✓Enable auth and use SCRAM-SHA-256 — default in MongoDB 7
- ✓Set up health checks and graceful shutdown — handle SIGTERM to drain in-flight requests before exit