A MongoDB replica set is a group of MongoDB instances that replicate the same data. In Kubernetes, each instance needs its own storage and a stable address so replicas can find one another after pod replacement. section 16.1.1
A Kubernetes deployment must provide:
- One PersistentVolume for each MongoDB pod, rather than sharing a volume among replicas. section 16.1.1
- A unique, stable address for every replica, preserved when a pod is deleted and recreated. section 16.1.1
- A StatefulSet with a volume-claim template to create individually named claims such as db-data-quiz-0 and db-data-quiz-1. section 16.1.4
Initialize three MongoDB replicas
After the three quiz pods and the quiz-pods Service exist, initialize the replica set with mongosh: rs.initiate({ _id: "quiz", members: [{_id: 0, host: "quiz-0.quiz-pods.kiada.svc.cluster.local:27017"}, {_id: 1, host: "quiz-1.quiz-pods.kiada.svc.cluster.local:27017"}, {_id: 2, host: "quiz-2.quiz-pods.kiada.svc.cluster.local:27017"}] }). A successful command returns { ok: 1 }; the pods then become ready after the quiz API can query MongoDB. section 16.1.4
$ kubectl exec -it quiz-0 -c mongo -- mongosh --quiet --eval 'rs.initiate({
_id: "quiz",
members: [
{_id: 0, host: "quiz-0.quiz-pods.kiada.svc.cluster.local:27017"},
{_id: 1, host: "quiz-1.quiz-pods.kiada.svc.cluster.local:27017"},
{_id: 2, host: "quiz-2.quiz-pods.kiada.svc.cluster.local:27017"}]})'
Inspect the complete mongosh initialization command, including the replica-set name and all three member addresses. section 16.1.4

