Home›Learn›MongoDB on Kubernetes: the Percona operator
MongoDB · High availability · Kubernetes

MongoDB on Kubernetes: the Percona operator

A replica set already elects its own primary. What is left for an operator to do?

The Percona Operator for MongoDB keeps a replica set or sharded cluster in the shape you declared, replaces lost pods, and runs backups with Percona Backup for MongoDB.

Why this tool exists

Why run MongoDB with an operator on Kubernetes

A MongoDB replica set already elects a new primary by itself. So what does an operator add? Everything around the election: creating members with the right volumes and certificates, replacing a lost member and re-adding it to the set, rolling a version change one member at a time, wiring backups to object storage, and building sharded clusters from config servers, shards and mongos. The Percona Operator for MongoDB does those jobs for Percona Server for MongoDB, from one custom resource.

What we are protecting

Writes and data on a replica set or sharded cluster while pods and nodes are replaced by Kubernetes.

What we achieve

A declared cluster (three members by default), automatic replacement of lost pods, rolling updates, and backups with Percona Backup for MongoDB (PBM): logical, physical, point-in-time recovery, and tech-preview incremental and PVC snapshot backups.

Where the election happens

Inside MongoDB, not the operator. The docs say Kubernetes reschedules a failed pod, mongod rejoins the replica set, and if the primary failed, the set elects a new one. See replica sets.

What it is not

Not a backup you have tested. A restore into a new cluster is the only proof.

The other operators, briefly

Pinned versions on this page: Percona Operator for MongoDB 1.23.1. The page assumes MongoDB 8.0 images; the exact Percona Server for MongoDB image tag comes from the cr.yaml of the operator tag.

How it was done before

Replacing a replica set member by hand

Say a replica set runs on three VMs and one dies for good. The set keeps working on two members, which is the point. But it is one failure from losing its majority, so you have work to do now.

  1. Provision a new host with the same MongoDB version, key file and TLS files.
  2. Open mongosh on the primary and run rs.status() to confirm the dead member and the current primary.
  3. Remove the dead member: rs.remove("old-host:27017").
  4. Start mongod on the new host with the same replica set name and an empty data directory.
  5. Add it: rs.add("new-host:27017"). It runs an initial sync, copying all data from another member.
  6. Watch rs.status() until it shows SECONDARY, then update your connection strings and monitoring.

Do this once and it is fine. Do it across fifty clusters and it is a project. For sharded clusters add config servers and mongos.

Step through it:

Explained clearly

What the Percona operator builds

1

The problem

You want a MongoDB cluster to be a declared object. "Three members, this storage, these backups" should be a file you keep in version control.

2

What it is

You install the operator, then create a PerconaServerMongoDB resource (psmdb.percona.com). Each replica set member runs in its own pod, in a StatefulSet that gives it a stable name and a PersistentVolume. PBM runs as a sidecar in each database pod once storage is configured. In a sharded cluster, mongos runs in its own StatefulSet and the config servers are a replica set with a dedicated role. The operator also creates the Services and DNS entries, and recommends mongodb+srv connection strings so drivers discover members through SRV records.

3

Follow one request

  1. The driver connects with the SRV connection string from the cluster secret.
  2. For a plain replica set, it finds the members and sends writes to the primary. For a sharded cluster, it talks to mongos, which routes to the shard.
  3. If a pod dies, Kubernetes reschedules it and the replica set elects a primary if needed.
  4. The driver rediscovers the primary and retries.
4

What to watch

  • The default cr.yaml deploys three mongod, three mongos and three config server pods with sharding enabled. For a plain replica set, turn sharding off in your copy.
  • Do not scale the StatefulSet with kubectl scale. The operator refuses it because the size options get out of sync. Change size in the custom resource.
  • Node anti-affinity spreads pods "when possible". Check that three members really sit on three nodes.

Step through it:

Step by step

Set it up

Pinned: Percona Operator for MongoDB 1.23.1 (it ships the image percona/percona-server-mongodb:8.0.32-14). You need a Kubernetes cluster with three schedulable nodes and a StorageClass.

kubectl create namespace mongodb
kubectl apply --server-side -f https://raw.githubusercontent.com/percona/percona-server-mongodb-operator/v1.23.1/deploy/bundle.yaml -n mongodb
kubectl apply -f https://raw.githubusercontent.com/percona/percona-server-mongodb-operator/v1.23.1/deploy/cr.yaml -n mongodb
kubectl get psmdb -n mongodb

The second command creates the three CRDs, a Role, ServiceAccount, RoleBinding and the operator Deployment. The third creates perconaservermongodb.psmdb.percona.com/my-cluster-name. Wait for STATUS to show ready.

For production, download deploy/cr.yaml from the same tag, edit it and apply your copy. The fields to set first:

apiVersion: psmdb.percona.com/v1
kind: PerconaServerMongoDB
metadata:
  name: orders
spec:
  crVersion: 1.23.1
  pause: false
  replsets:
  - name: rs0
    size: 3
  sharding:
    enabled: false          # a plain replica set; the default file enables sharding
  backup:
    enabled: true
    pitr:
      enabled: false        # turn on after the first full backup

Replace the default passwords before production: the docs warn that default passwords are set for the required users. Get credentials and the SRV connection string from the cluster's secret.

Backups

Set storage under backup.storages. Supported remotes: Amazon S3, Google Cloud Storage, MinIO and S3-compatible, Azure Blob, Alibaba OSS, OCI Object Storage, and a remote file server. Several storages are supported from 1.20.0. PBM does the copy: the operator writes a document to PBM control collections and a pbm-agent on a secondary does the work.

TypeStatusNotes
Full logicalGAPortable, supports selective restore and PITR, slower to restore than physical.
Full physicalGA since 1.16.0Copies files from dbPath. Suits large data sets. PITR since 1.15.0.
Physical incrementalTech preview since 1.20.0Needs a base backup; increments run on the same node.
PVC snapshot (external)Tech preview since 1.23.0Needs the Volume Snapshot API. No PITR, no selective restore.

Point-in-time recovery: set backup.pitr.enabled after a full backup. It works with logical and physical backups only, and you need a fresh full backup for a new cluster and after every restore. Retention is controlled by backup.tasks.retention. Backup objects carry a delete-backup finalizer, so deleting the object also deletes the files in storage. Restores can go into the same cluster (backupName) or a new one (backupSource).

When it breaks

A primary pod dies

A three-member replica set, rs0, one member per node. The node under the primary fails.

Step through it:

Planned work: change size or the image in the custom resource and apply it. Members are updated one at a time. To move the primary before maintenance, use the normal MongoDB step-down on the primary: rs.stepDown() in mongosh.

Day to day

The commands you will actually run

NS is the namespace and NAME the cluster name (my-cluster-name in the default file).

Status

kubectl get psmdb -n NS                                        # state; wait for ready
kubectl get pods -n NS -l app.kubernetes.io/replset=rs0        # members of rs0
kubectl get pods -n NS -l app.kubernetes.io/component=mongod   # all mongod pods
kubectl get pods -n NS -l app.kubernetes.io/component=mongos   # mongos pods (sharded)
kubectl get pods -n NS -l app.kubernetes.io/replset=cfg        # config servers (sharded)

Scale

Set size under the replica set in the custom resource and apply it. Do not use kubectl scale statefulset.

kubectl apply -f deploy/cr.yaml -n NS                          # after editing replsets[].size
kubectl patch psmdb NAME -n NS --type=json -p='[{"op":"replace","path":"/spec/replsets/0/size","value":5}]'

Config servers use sharding.configsvrReplSet.size, mongos uses sharding.mongos.size. A shard is another entry in spec.replsets. The operator blocks removing a shard that still holds user collections, so migrate its data first. Keep replica set member counts odd.

Pause and resume

kubectl patch psmdb NAME -n NS --type=merge -p '{"spec":{"pause":true}}'
kubectl patch psmdb NAME -n NS --type=merge -p '{"spec":{"pause":false}}'

The docs show spec.pause: true in cr.yaml as the way to stop the cluster gracefully, and false to start it again. Take a backup first.

Restore

Restore into a new cluster to test a backup. Use backupName when the Backup object still exists in the cluster, and backupSource when it does not. You can restore with different replica set names, restore selected namespaces from a full logical backup, or restore a collection under a new name (logical, replica sets only).

What goes wrong

Failures to plan for

SymptomLikely causeFirst checkFix
Cluster not ready after applyPending pods (no capacity, no StorageClass), or wrong crVersion.kubectl get pods, describe pod, operator logs.Fix capacity or storage, set crVersion to match the operator.
Two members down of threeNo majority: no primary, writes stop.kubectl get pods, rs.status().Bring the pods back. Do not re-initiate the set on one member unless you accept data loss and know which member is newest.
Scale change ignored or revertedUsed kubectl scale on the StatefulSet.status.size in the custom resource.Change size in the custom resource.
Backup stays starting or failsWrong credentials, bucket permissions, PBM agent unhealthy.Backup resource status, PBM logs in the pod.Fix storage config. Take a new full backup.
PITR gap or error after a restoreNo new full backup after a restore or new cluster.PBM status.Take a full backup, then re-enable PITR.
Failed restore leaves odd dataThe docs say consistency is not guaranteed after a failed restore.Restore resource status.Restore again into a clean new cluster.
Deleted a backup object and lost the filesThe delete-backup finalizer removes files from storage.Storage listing.Do not delete backup objects casually. Use retention settings.
Two pods on one nodeAnti-affinity is "when possible".Pod placement.Add nodes or tighten affinity so one node loss cannot take a majority.
Monitoring

What to watch, and from where

SignalWhereAlert when
Cluster statekubectl get psmdb or kube-state-metricsNot ready for more than a few minutes.
Member states and primaryrs.status(), mongodb exporter or PMMNo primary, a member in RECOVERING or UNKNOWN for long.
Replication lag and oplog windowrs.printSecondaryReplicationInfo(), exporterLag above your RPO. Oplog window shorter than your longest maintenance.
Backup and PITR statusBackup resources, PBMNo successful backup in the window, PITR stopped.
PVC use and pod restartskubelet metricsAbove 80 percent, restart loops.
Chunk balance, mongos health (sharded)sh.status(), mongos podsUneven chunks, mongos not ready.

Percona lists a PMM client as an optional sidecar for replica set, config server and mongos pods. Related pages: replica sets, running MongoDB, running 1,000 databases.

Hands off

Let the agent do it

Every change is shown to you first and runs only after you type an approval. Reads run straight away.

python3 -m dbagent.ha k8s status --kind psmdb --name CLUSTER -n NS
python3 -m dbagent.ha k8s pause --kind psmdb --name CLUSTER -n NS
python3 -m dbagent.ha k8s resume --kind psmdb --name CLUSTER -n NS
python3 -m dbagent.ha k8s scale --kind psmdb --name CLUSTER --size N -n NS

pause and resume set spec.pause. scale sets the replica set size in the custom resource, not the StatefulSet. The same commands take --kind pxc and --kind ps for MySQL.

Where this came from

Sources

Part 1 of 4 · Learn · 56 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.

Start 1: the basicsStart 2: ten conceptsStart 3: how a query travelsStart 4: napkin mathThe courseShort videosPostgreSQL 1: why PostgreSQLPostgreSQL 2: how it stores your dataPostgreSQL 3: what happens on every writePostgreSQL 4: high availability with PatroniPostgreSQL 5: running it as a DBREPostgreSQL 6: when it breaksPostgreSQL on Kubernetes: CloudNativePGMySQL 1: why MySQLMySQL 2: how it stores your dataMySQL 3: what happens on every writeMySQL 4: high availability with InnoDB ClusterMySQL 5: running it as a DBREMySQL 6: when it breaksMySQL failover with OrchestratorMySQL on Kubernetes: the Percona operatorsMongoDB 1: why MongoDBMongoDB 2: how it stores your dataMongoDB 3: what happens on every writeMongoDB 4: high availability with replica setsMongoDB 5: running it as a DBREMongoDB 6: when it breaksMongoDB on Kubernetes: the Percona operatorB-tree and LSM treeRedis 1: why RedisRedis 2: how it stores your dataRedis 3: high availabilityRedis 4: running it as a DBRERedis 5: when it breaksCassandra 1: why CassandraCassandra 2: how it stores your dataCassandra 3: high availabilityCassandra 4: running it as a DBRECassandra 5: when it breaksVector databases 1: why vector searchVector databases 2: how it stores your dataVector databases 3: high availabilityVector databases 4: running it as a DBREVector databases 5: when it breaksDatabase familiesEngines side by sideQueries that look fine and are notLost updates and write skewMany servers 1: keep a copy runningMany servers 2: who is the leaderMany servers 3: CAP as settingsMany servers 4: unique IDsMany servers 5: split the dataMany servers 6: across servicesMany servers 7: a thousand databasesStaff path, zero to architect