liveBook · Manning

MongoDB replica set

As explained in Kubernetes in Action, Second Edition

A MongoDB replica set is a group of MongoDB server instances that maintain replicated data and designate a primary for write operations.

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

How Kubernetes in Action, Second Edition covers it

How deep it goes
Explains storage and addressing requirements, StatefulSet artifacts, initialization, readiness failures, and inspection commands.
Examples
Uses a three-pod quiz deployment, per-pod claims, stable DNS names, and an rs.initiate command.
What you can do after
Operate/configure a three-member replica set with kubectl, mongosh, stable Services, and per-pod persistent claims.
How it connects
Connects MongoDB replica sets to StatefulSets, Pods, PersistentVolumeClaims, Services, and readiness probes.

Also explained in

Compare how 2 books explain MongoDB replica set →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kubernetes in Action, Second Edition. The section links point to the parts of the book it draws on.