mongodb

by ScriptonBasestar

Helm chartv0.4.0App 7.0.14

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

ParameterDescriptionDefault
replicaCountNumber of MongoDB replicas1
mongodb.databaseInitial database nameadmin
mongodb.rootPasswordRoot password (auto-generated if empty)""
mongodb.auth.enabledEnable authenticationtrue
mongodb.wiredTiger.cacheSizeGBWiredTiger cache size0.25
mongodb.replicaSet.enabledEnable replica setfalse
mongodb.replicaSet.nameReplica set namers0
mongodb.replicaSet.keyReplica set key""
persistence.enabledEnable persistencetrue
persistence.sizePVC storage size10Gi
persistence.storageClassPVC storage class""
resources.limits.memoryMemory limit1Gi
resources.limits.cpuCPU limit1000m

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

  1. 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)
  1. Check replica set status:
make -f make/ops/mongodb.mk mongo-rs-status
  1. 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

  1. Verify service:
kubectl get svc my-mongodb
  1. Test connection:
make -f make/ops/mongodb.mk mongo-ping

Performance Issues

  1. Check resource usage:
kubectl top pod mongodb-0
  1. Increase WiredTiger cache:
mongodb:
  wiredTiger:
    cacheSizeGB: 2.0  # 50-80% of available memory

Backup & Recovery

Backup Strategy

MongoDB backups consist of 4 primary components:

ComponentPriorityMethodRTORPO
Database DataCriticalmongodump, snapshots< 1 hour24 hours
OplogCriticalmongodump --oplog< 30 min15 minutes
ConfigurationImportantConfigMap/Secret export< 15 min24 hours
Users & RolesImportantmongodump --authenticationDatabase< 15 min24 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 ScenarioRTO (Recovery Time)RPO (Recovery Point)
Full Database< 1 hour24 hours
Point-in-Time (PITR)< 1 hour15 minutes
Selective Database< 30 minutes24 hours
Configuration< 15 minutes24 hours
Users & Roles< 15 minutes24 hours
Disaster Recovery< 2 hours24 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.

  1. Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
  2. Place the chartmongodb is pinned at v0.4.0 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
  3. 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