mongodb
MongoDB NoSQL database with replica set support
About this chart
MongoDB Helm Chart
MongoDB NoSQL database with replica set support for Kubernetes
Features
- StatefulSet Deployment: Stable pod identities with persistent storage
- Replica Set Support: Automatic replica set initialization and management
- Persistent Storage: PersistentVolumeClaim with configurable storage class
- Configuration Management: Complete mongod.conf via ConfigMap
- Security: Authentication enabled, secrets for passwords, non-root execution
- Health Probes: Liveness and readiness using mongosh
- Resource Management: Configurable CPU/memory limits
- Operational Tools: 40+ Makefile commands for database management
TL;DR
# Add the repository
helm repo add scripton-charts https://scriptonbasestar-container.github.io/sb-helm-charts
helm repo update
# Install single node
helm install my-mongodb scripton-charts/mongodb
# Install replica set (3 members)
helm install my-mongodb scripton-charts/mongodb \
--set replicaCount=3 \
--set mongodb.replicaSet.enabled=true \
--set mongodb.rootPassword=securePassword \
--set mongodb.replicaSet.key=your32CharacterReplicaSetKey
Prerequisites
- Kubernetes 1.19+
- Helm 3.0+
- PV provisioner support
Installing the Chart
Basic Installation
helm install my-mongodb scripton-charts/mongodb
Development Installation
helm install my-mongodb scripton-charts/mongodb \
-f https://raw.githubusercontent.com/scriptonbasestar-container/sb-helm-charts/master/charts/mongodb/values-dev.yaml
Production with Replica Set
helm install my-mongodb scripton-charts/mongodb \
-f https://raw.githubusercontent.com/scriptonbasestar-container/sb-helm-charts/master/charts/mongodb/values-small-prod.yaml \
--set mongodb.rootPassword=securePassword \
--set mongodb.replicaSet.key=your32CharacterReplicaSetKey
Uninstalling the Chart
helm uninstall my-mongodb
Note: PVCs are not auto-deleted. Delete manually if needed:
kubectl delete pvc -l app.kubernetes.io/instance=my-mongodb
Configuration
Key Parameters
| Parameter | Description | Default |
|---|---|---|
replicaCount | Number of MongoDB replicas | 1 |
mongodb.database | Initial database name | admin |
mongodb.rootPassword | Root password (auto-generated if empty) | "" |
mongodb.auth.enabled | Enable authentication | true |
mongodb.wiredTiger.cacheSizeGB | WiredTiger cache size | 0.25 |
mongodb.replicaSet.enabled | Enable replica set | false |
mongodb.replicaSet.name | Replica set name | rs0 |
mongodb.replicaSet.key | Replica set key | "" |
persistence.enabled | Enable persistence | true |
persistence.size | PVC storage size | 10Gi |
persistence.storageClass | PVC storage class | "" |
resources.limits.memory | Memory limit | 1Gi |
resources.limits.cpu | CPU limit | 1000m |
Replica Set Architecture
┌──────────────────┐
│ mongodb-0 │
│ (Primary) │
│ Read + Write │
└────────┬─────────┘
│ Oplog replication
├──────────────┬────────────────┐
│ │ │
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ mongodb-1 │ │ mongodb-2 │ │ mongodb-N │
│ (Secondary) │ │ (Secondary) │ │ (Secondary) │
│ Read Only │ │ Read Only │ │ Read Only │
└──────────────┘ └──────────────┘ └──────────────┘
Replica Set Setup
- Install with odd number of members (3, 5, or 7 recommended):
helm install my-mongodb scripton-charts/mongodb \
--set replicaCount=3 \
--set mongodb.replicaSet.enabled=true \
--set mongodb.replicaSet.name=rs0 \
--set mongodb.rootPassword=myPassword \
--set mongodb.replicaSet.key=$(openssl rand -base64 24)
- Check replica set status:
make -f make/ops/mongodb.mk mongo-rs-status
- Connection URI for applications:
mongodb://mongodb-0.mongodb-headless:27017,mongodb-1.mongodb-headless:27017,mongodb-2.mongodb-headless:27017/mydb?replicaSet=rs0
Backup and Restore
Backup
make -f make/ops/mongodb.mk mongo-backup
This creates a compressed backup in tmp/mongodb-backups/.
Restore
make -f make/ops/mongodb.mk mongo-restore FILE=tmp/mongodb-backups/mongodb-backup-20240101.gz
Operational Commands
Basic Operations
make -f make/ops/mongodb.mk mongo-shell
make -f make/ops/mongodb.mk mongo-logs
make -f make/ops/mongodb.mk mongo-port-forward
Database Management
make -f make/ops/mongodb.mk mongo-list-dbs
make -f make/ops/mongodb.mk mongo-list-collections DB=mydb
make -f make/ops/mongodb.mk mongo-db-stats DB=mydb
Replica Set Operations
make -f make/ops/mongodb.mk mongo-rs-status
make -f make/ops/mongodb.mk mongo-rs-config
make -f make/ops/mongodb.mk mongo-rs-stepdown
User Management
make -f make/ops/mongodb.mk mongo-create-user DB=mydb USER=myuser PASSWORD=mypass ROLE=readWrite
make -f make/ops/mongodb.mk mongo-list-users DB=mydb
Performance Monitoring
make -f make/ops/mongodb.mk mongo-server-status
make -f make/ops/mongodb.mk mongo-current-ops
make -f make/ops/mongodb.mk mongo-top
For complete list:
make -f make/ops/mongodb.mk help
Troubleshooting
Replica Set Not Initializing
Check pod logs:
kubectl logs mongodb-0 -c setup-replica-set
Manually initialize:
make -f make/ops/mongodb.mk mongo-rs-initiate POD=mongodb-0
Connection Issues
- Verify service:
kubectl get svc my-mongodb
- Test connection:
make -f make/ops/mongodb.mk mongo-ping
Performance Issues
- Check resource usage:
kubectl top pod mongodb-0
- Increase WiredTiger cache:
mongodb:
wiredTiger:
cacheSizeGB: 2.0 # 50-80% of available memory
Backup & Recovery
Backup Strategy
MongoDB backups consist of 4 primary components:
| Component | Priority | Method | RTO | RPO |
|---|---|---|---|---|
| Database Data | Critical | mongodump, snapshots | < 1 hour | 24 hours |
| Oplog | Critical | mongodump --oplog | < 30 min | 15 minutes |
| Configuration | Important | ConfigMap/Secret export | < 15 min | 24 hours |
| Users & Roles | Important | mongodump --authenticationDatabase | < 15 min | 24 hours |
Quick Backup Commands
# Full backup (all components)
make -f make/ops/mongodb.mk mongo-full-backup
# Database backup
make -f make/ops/mongodb.mk mongo-backup-database
# Oplog backup (replica sets)
make -f make/ops/mongodb.mk mongo-backup-oplog
# Configuration backup
make -f make/ops/mongodb.mk mongo-backup-config
# Users & roles backup
make -f make/ops/mongodb.mk mongo-backup-users
# List available backups
make -f make/ops/mongodb.mk mongo-backup-status
Backup Methods
1. mongodump (Recommended)
- Regular backups with selective database support
- Oplog support for point-in-time recovery (PITR)
- Works with any MongoDB version
- Human-readable BSON/JSON format
# Full backup with oplog (replica sets)
POD=$(kubectl get pods -n default -l app.kubernetes.io/name=mongodb -o jsonpath='{.items[0].metadata.name}')
kubectl exec -n default $POD -- mongodump \
--username=root \
--password=$MONGO_ROOT_PASSWORD \
--authenticationDatabase=admin \
--oplog \
--gzip \
--out=/tmp/backup
2. PVC Snapshots (VolumeSnapshot)
- Fast storage-level snapshots
- Requires CSI driver support
- Instant snapshot creation
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
name: mongodb-snapshot-20250109
spec:
volumeSnapshotClassName: csi-snapclass
source:
persistentVolumeClaimName: data-mongodb-0
3. Filesystem Copy
- Simple and fast for small databases
- Requires database lock for consistency
# Lock database, copy, unlock
kubectl exec -n default $POD -- mongo admin --eval "db.fsyncLock()"
kubectl exec -n default $POD -- tar czf /tmp/data-backup.tar.gz /data/db
kubectl exec -n default $POD -- mongo admin --eval "db.fsyncUnlock()"
4. Replica Set Delayed Secondary
- Continuous replication with time delay
- Protection against logical errors
- Requires replica set configuration
5. MongoDB Cloud Manager / Ops Manager
- Enterprise automated backups
- Point-in-time recovery
- Centralized management
Recovery Procedures
Full Database Restore:
# Restore from mongodump backup
make -f make/ops/mongodb.mk mongo-restore-database FILE=/backups/mongodb/20250109/
# Manual restore
POD=$(kubectl get pods -n default -l app.kubernetes.io/name=mongodb -o jsonpath='{.items[0].metadata.name}')
kubectl cp /backups/mongodb/20250109/ $POD:/tmp/restore/
kubectl exec -n default $POD -- mongorestore --drop /tmp/restore/
Point-in-Time Recovery (PITR):
# Restore base backup + apply oplog to specific timestamp
kubectl exec -n default $POD -- mongorestore --drop /tmp/restore/base-backup/
kubectl exec -n default $POD -- mongorestore \
--oplogReplay \
--oplogLimit="1641024000:1" \
/tmp/restore/oplog/
Selective Database/Collection Restore:
# Restore specific database
kubectl exec -n default $POD -- mongorestore \
--db=myapp \
--drop \
/tmp/restore/myapp/
# Restore specific collection
kubectl exec -n default $POD -- mongorestore \
--db=myapp \
--collection=users \
/tmp/restore/myapp/users.bson
RTO/RPO Targets
| Recovery Scenario | RTO (Recovery Time) | RPO (Recovery Point) |
|---|---|---|
| Full Database | < 1 hour | 24 hours |
| Point-in-Time (PITR) | < 1 hour | 15 minutes |
| Selective Database | < 30 minutes | 24 hours |
| Configuration | < 15 minutes | 24 hours |
| Users & Roles | < 15 minutes | 24 hours |
| Disaster Recovery | < 2 hours | 24 hours |
For comprehensive backup/recovery procedures, see: MongoDB Backup Guide
Security & RBAC
RBAC Resources
This chart includes namespace-scoped RBAC resources:
Role: Grants read-only access to:
- ConfigMaps (configuration management)
- Secrets (credential access)
- Pods (health checks and operations)
- Services (service discovery)
- Endpoints (service discovery)
- PersistentVolumeClaims (storage operations)
RoleBinding: Binds the Role to the ServiceAccount
ServiceAccount: Pod identity for MongoDB operations
RBAC Configuration
rbac:
# Enable/disable RBAC resource creation
create: true
# Custom annotations for Role and RoleBinding
annotations:
description: "MongoDB operational permissions"
Security Best Practices
DO:
- ✅ Enable authentication (
mongodb.auth.enabled: true) - ✅ Use strong passwords (16+ characters, random)
- ✅ Store credentials in Kubernetes Secrets
- ✅ Enable TLS/SSL for production
- ✅ Use RBAC to restrict access
- ✅ Run as non-root user (UID 999)
- ✅ Enable network policies
- ✅ Rotate credentials regularly
- ✅ Enable audit logging
- ✅ Use replica sets for HA
DON'T:
- ❌ Use default passwords
- ❌ Disable authentication
- ❌ Run as root user
- ❌ Expose MongoDB directly to internet
- ❌ Store passwords in values.yaml
- ❌ Skip TLS in production
- ❌ Use overly permissive RBAC roles
Pod Security Context
podSecurityContext:
fsGroup: 999 # MongoDB group
runAsUser: 999 # MongoDB user
runAsNonRoot: true # Enforce non-root
securityContext:
capabilities:
drop:
- ALL # Drop all capabilities
readOnlyRootFilesystem: false # MongoDB needs writable /tmp
allowPrivilegeEscalation: false
NetworkPolicy Example
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: mongodb-network-policy
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: mongodb
policyTypes:
- Ingress
- Egress
ingress:
# Allow from application pods
- from:
- podSelector:
matchLabels:
app: myapp
ports:
- protocol: TCP
port: 27017
# Allow from same namespace (replica set)
- from:
- podSelector:
matchLabels:
app.kubernetes.io/name: mongodb
ports:
- protocol: TCP
port: 27017
egress:
# Allow DNS
- to:
- namespaceSelector:
matchLabels:
name: kube-system
ports:
- protocol: UDP
port: 53
# Allow replica set communication
- to:
- podSelector:
matchLabels:
app.kubernetes.io/name: mongodb
ports:
- protocol: TCP
port: 27017
TLS/SSL Configuration
mongodb:
config:
net:
tls:
mode: requireTLS
certificateKeyFile: /etc/mongodb/certs/mongodb.pem
CAFile: /etc/mongodb/certs/ca.pem
extraVolumes:
- name: mongodb-certs
secret:
secretName: mongodb-tls
defaultMode: 0400
extraVolumeMounts:
- name: mongodb-certs
mountPath: /etc/mongodb/certs
readOnly: true
Verify RBAC
# Check Role
kubectl get role mongodb-role -n default -o yaml
# Check RoleBinding
kubectl get rolebinding mongodb-rolebinding -n default -o yaml
# Check ServiceAccount
kubectl get serviceaccount mongodb -n default -o yaml
# Test permissions
kubectl auth can-i get pods --as=system:serviceaccount:default:mongodb -n default
Operations
Daily Operations
Access MongoDB:
# Port forward to localhost
make -f make/ops/mongodb.mk mongo-port-forward
# Access at: mongodb://localhost:27017
# Get connection string
make -f make/ops/mongod
Deploy mongodb with OpenTenant
Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has mongodb on a Hetzner server. Change the host, add apps from the marketplace, then copy the generated files. Providers and prices are samples, and nothing here is sent anywhere.
- Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
- Place the chartmongodb is pinned at v0.4.0 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
- ApplySave opentenant.yaml and main.tf from the console, then run the commands below.
# opentenant.yaml, main.tf and dns.tf come from the builder below opentenant validate opentenant.yaml terraform init && terraform apply