How do you run MongoDB on Kubernetes?
IntermediateHands-onMongoDB
Answer
Short answer
For anything beyond a quick test, use an operator — the MongoDB Community/Enterprise Operator or Percona Operator for MongoDB — which creates a replica set as a StatefulSet with persistent volumes, handles initialisation, users, TLS, scaling and backups. Each member gets a stable DNS name.
Why a StatefulSet?
- Stable pod names (
mongo-0,mongo-1,mongo-2) and DNS via a headless Service:mongo-0.mongo.db.svc.cluster.local. - Each pod keeps its own PVC across restarts.
- Ordered startup and updates.
Percona Operator example (simplified)
apiVersion: psmdb.percona.com/v1
kind: PerconaServerMongoDB
metadata: { name: shop-mongo }
spec:
image: percona/percona-server-mongodb:7.0
replsets:
- name: rs0
size: 3
volumeSpec:
persistentVolumeClaim: { resources: { requests: { storage: 50Gi } } }
affinity: { antiAffinityTopologyKey: topology.kubernetes.io/zone }
backup:
enabled: true
storages:
s3: { type: s3, s3: { bucket: shop-mongo-backups, region: ap-south-1 } }
App connection
mongodb://app:***@shop-mongo-rs0-0.shop-mongo-rs0.db.svc,shop-mongo-rs0-1...,shop-mongo-rs0-2.../shop?replicaSet=rs0
What to say in the interview
"I'd use an operator that runs a three-member replica set as a StatefulSet with a PVC per member, anti-affinity across zones, TLS, users and scheduled backups to object storage. Apps use the headless-service DNS names in a replicaSet connection string."