Whitepapers / MongoDB on Kubernetes

Running MongoDB on Kubernetes

Replica sets, sharded clusters, and operators

MongoDB was built to be distributed. Drivers discover the topology themselves, replica sets elect their own primary, and sharding is part of the server. That makes it a natural fit for Kubernetes, as long as you get a few things right.

For DBAs, SREs, and platform engineers. Covers MongoDB 7.0 and later.

1. Introduction: MongoDB meets Kubernetes

MongoDB is the most widely used document database. Running it on Kubernetes puts it next to the applications it serves, defined in the same declarative way and managed with the same tools, on infrastructure you control.

Is MongoDB on Kubernetes production-ready?

Yes. The Percona Operator for MongoDB has been generally available since 2019 and supports replica sets, sharded clusters, and point-in-time recovery. MongoDB, Inc. ships its own operator, MongoDB Controllers for Kubernetes, which is how it supports Enterprise Advanced customers on Kubernetes.

MongoDB also does much of the hard work itself. Failover is built into the server, so a replica set elects a new primary without any external tooling, and drivers find the new primary on their own. On Kubernetes, the operator only has to keep the pods, volumes, and configuration in the right shape.

Compared with VM-based deployments or a managed service, running MongoDB on Kubernetes has three main advantages:

  1. It avoids vendor lock-in. The same cluster runs on AWS, GCP, Azure, or bare metal, and data and backups stay in accounts you own. It is the main self-hosted alternative to MongoDB Atlas.
  2. Operations are automated. Operators handle provisioning, rolling upgrades, scaling, TLS certificates, and backups through Kubernetes resources instead of runbooks.
  3. It costs less. You pay for compute and storage instead of a managed-service premium, and you can consolidate workloads on shared clusters and right-size them.

The real decisions are which topology, how to size memory and storage, and which operator to use. This guide covers each of them.

A note on licensing

The operators covered here are open source under Apache 2.0. The database server is not: MongoDB Community Server, and Percona Server for MongoDB, which is a drop-in replacement for it, are licensed under the Server Side Public License (SSPL). Running MongoDB for your own applications, including SaaS products that use it as their database, is fine. The SSPL's service clause applies when you offer MongoDB itself as a service to third parties. Our comparison with MongoDB Atlas covers this in more detail.

2. MongoDB on Kubernetes architectures

MongoDB has two production topologies. A replica set is a group of servers that hold the same data, with automatic failover. A sharded cluster splits the data across several replica sets and puts query routers in front of them. Most deployments should start with a replica set.

Replica sets: the driver is the router

A replica set has one primary, which takes all writes, and usually two secondaries, which copy the primary's oplog (operations log) and apply the same changes. Three members is the minimum for automatic failover, because an election needs a majority of votes.

Unlike PostgreSQL, MongoDB does not need a proxy or a connection pooler in front of a replica set. The driver connects to the seed hosts you give it, discovers every member, and keeps a connection pool to each one. It sends writes to the primary, routes reads according to your read preference, and notices on its own when the primary changes.

mongodb://app:****@rs0-0.rs0.db.svc:27017,rs0-1.rs0.db.svc:27017,rs0-2.rs0.db.svc:27017/?replicaSet=rs0

Inside the Kubernetes cluster, you can also use a mongodb+srv:// URI that points to the replica set's headless Service, so the member list never has to be written out.

Application (MongoDB driver)connects to every memberZone AZone BZone CPrimary (read/write)SecondarySecondaryrs0-0 · node-1rs0-1 · node-2rs0-2 · node-3Persistent volumePersistent volumePersistent volumeoplog replication
A three-member replica set across three zones. The driver holds connections to every member, so no proxy is needed. Secondaries pull the primary's oplog and apply it to their own volumes. If a zone goes down, the two remaining members still form a majority and elect a new primary.

Read preference

The read preference in the connection string tells the driver where to send reads. Reads from secondaries can return slightly stale data, so only use them where that is acceptable, such as reporting.

ModeWhere reads go
primaryAlways the primary. The default, with the strongest consistency.
primaryPreferredThe primary, or a secondary if no primary is available.
secondaryOnly secondaries. Useful for analytics that shouldn't load the primary.
secondaryPreferredSecondaries, or the primary if no secondary is available.
nearestThe member with the lowest network latency, primary or secondary.

Elections and failover

MongoDB's replication protocol is based on Raft. Members exchange heartbeats every two seconds. If the secondaries can't reach the primary for electionTimeoutMillis (10 seconds by default), one of them calls an election, and a member with an up-to-date oplog wins with a majority of votes. With default settings, a new primary is usually elected in under 12 seconds.

Applications barely notice. Modern drivers retry a failed write once after a failover, and since MongoDB 5.0 the default write concern is w: "majority", so an acknowledged write is already on a majority of members and survives the failover.

Avoid arbiters in production. An arbiter votes in elections but holds no data, so a primary-secondary-arbiter set keeps only two copies of your data, and its default write concern drops to w: 1. Three data-bearing members cost a little more and are much safer. For analytics or backup-only members, add them as hidden members with priority: 0 so they can never become primary.

Multi-AZ deployments

Spread the three members of each replica set across three availability zones, so that losing a whole zone still leaves a majority. With only two zones, the zone holding two members takes the majority with it when it fails. With the Percona Operator, one field sets this:

replsets:
- name: rs0
  size: 3
  affinity:
    antiAffinityTopologyKey: topology.kubernetes.io/zone

Connecting from outside Kubernetes

This is the most common surprise when moving MongoDB to Kubernetes. The replica set configuration stores a hostname for each member, and after discovery the driver connects to those names, not to the address you gave it. A single load balancer in front of the replica set doesn't work: clients outside the cluster get back internal pod DNS names they can't resolve.

There are two ways around it. Expose each member through its own Service, which operators do for you when you enable external access, so every member has an address that is reachable from outside. Or configure split horizon, so members advertise internal names to clients inside the cluster and external names to clients outside it. Clients that only need one member, such as an admin shell, can use directConnection=true, but they lose automatic failover.

Sharded clusters: scaling out with mongos

When one replica set is no longer enough, a sharded cluster splits collections across several shards. Each shard is a full replica set. Applications connect to mongos routers, which are stateless and send each operation to the right shard. The routing metadata, meaning which ranges of data (chunks) live on which shard, is kept in a dedicated config server replica set.

Because mongos is stateless, you can put an ordinary Kubernetes Service or load balancer in front of the routers, and add routers as application traffic grows.

Application (MongoDB driver)mongosmongosstateless routerstateless routerchunk metadatareads and writesConfig server RSShard 1 (rs0)Shard 2 (rs1)PrimarySecondarySecondaryPrimarySecondarySecondaryPrimarySecondarySecondary
A sharded cluster with two shards. Applications only talk to the mongos routers, which use the config servers' chunk metadata to send each operation to the right shard. Each replica set spreads its members across three zones, as in the previous figure.

Shard when a single primary can no longer keep up with writes, when the working set no longer fits in one server's memory, or when the dataset is so large that backups and initial syncs take too long. Zone sharding, which pins ranges of data to specific regions, is another reason. Don't shard early, though. It adds a config server replica set, routers, a balancer, and a shard key you have to live with. Scaling a replica set up is simpler and goes a long way.

The config server replica set

The config servers are a regular replica set, normally with three members, and they don't support arbiters. They hold little data but are critical. If the config server replica set loses its primary, the cluster's metadata becomes read-only: applications can still read and write, but chunk migrations, splits, and other metadata changes stop until a primary is back. If all config servers are lost, the cluster can't operate. Back them up together with the shards, which PBM does for you.

Since MongoDB 8.0, a config server replica set can also store application data as a config shard. For small sharded clusters this saves a separate set of three pods.

sharding:
  enabled: true
  configsvrReplSet:
    size: 3
    affinity:
      antiAffinityTopologyKey: topology.kubernetes.io/zone
  mongos:
    size: 3

Choosing a shard key

The shard key decides how documents are spread across shards, and most sharding problems come back to it. A good key has high cardinality, spreads writes evenly, and matches your most common queries, so that they go to a single shard instead of all of them.

Shard keyResult
{ userId: "hashed" }Writes spread evenly. Range queries on userId have to go to every shard.
{ tenantId: 1, _id: 1 }Each tenant's data stays together, and queries per tenant go to one shard.
{ createdAt: 1 }Monotonic. Every insert lands on the same shard, which becomes a hotspot.
{ status: 1 }Low cardinality. Chunks can't be split, so data can't be balanced.

A shard key isn't permanent anymore. MongoDB 5.0 and later can reshard a collection online with reshardCollection, but it rewrites the whole collection, so it is better to choose carefully the first time.

3. Compute and storage strategy

MongoDB performance comes down mostly to memory: whether the working set fits in the WiredTiger cache. Storage latency matters for checkpoints and for anything that misses the cache. On Kubernetes, both depend on how you set resources and storage classes.

Guaranteed QoS (requests equal limits)

For stateless apps, low requests and high limits are a standard way to pack more pods onto each node. For databases, this causes problems. If the memory limit is higher than the request, the Linux OOM killer targets the database pod first when the node runs low on memory.

Set requests equal to limits for CPU and memory on every replica set member, including secondaries and config servers. This puts the pods in the Guaranteed QoS class. Any secondary can become the primary at the next election, so it needs the same resources and the same protection.

replsets:
- name: rs0
  resources:
    requests:
      cpu: "4"
      memory: 16Gi
    limits:
      cpu: "4"
      memory: 16Gi
QoS classWhen a pod gets it
GuaranteedRequests equal limits
BurstableRequests lower than limits
BestEffortNo requests or limits set

WiredTiger cache sizing

WiredTiger, MongoDB's storage engine, keeps recently used data and indexes in its own cache. By default, the cache takes 50% of (RAM − 1 GB), or 256 MB, whichever is larger. Current MongoDB versions use the container's memory limit as RAM for this calculation. Older versions, or unusual cgroup setups, can pick up the node's memory instead, size the cache far beyond the container limit, and get the pod OOM-killed.

Set the cache explicitly and check it after deployment with db.serverStatus().wiredTiger.cache["maximum bytes configured"]. The Percona Operator calculates the cache from the container limit for you with cacheSizeRatio.

# mongod configuration,
# 16 GiB container
storage:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 7.5

Plain mongod: 0.5 × (16 − 1) GB.

replsets:
- name: rs0
  storage:
    wiredTiger:
      engineConfig:
        cacheSizeRatio: 0.5

Percona Operator: derived from the memory limit.

Don't raise the cache to most of the container's memory. The rest is needed for the filesystem cache, which holds compressed data files, for connections at roughly 1 MB each, and for aggregations and index builds.

Oplog sizing

The oplog is a capped collection that records every write. Its size sets the replication window: how long a secondary can be down, or how long an initial sync can take, and still catch up. A member that falls behind the oldest oplog entry has to resync all of its data from scratch.

By default, the oplog takes 5% of free disk space, at least 990 MB and at most 50 GB. Size it so the window covers at least a day of normal writes, and comfortably more than your longest maintenance or node replacement. The oplog size doesn't limit point-in-time recovery: PBM copies the oplog to object storage continuously, so the recovery window depends on how long you keep backups.

replication:
  oplogSizeMB: 51200   # 50 GB, set in megabytes

Check the current window with rs.printReplicationInfo(). Since MongoDB 4.4, storage.oplogMinRetentionHours can keep entries for a minimum time even if the oplog grows past its configured size, so watch disk usage if you use it.

Network-attached storage (EBS, Ceph)

The standard approach is to separate storage from compute with network-attached volumes such as AWS EBS, GCP Persistent Disk, or Ceph. When a node fails, the pod is rescheduled on another node and the same PersistentVolume is re-attached with all its data. The member only has to catch up on the oplog it missed.

The trade-off is I/O latency, which is higher than local disk. For most MongoDB workloads, network storage with enough provisioned IOPS is the right default.

Local NVMe SSDs

WiredTiger writes checkpoints every 60 seconds and reads from disk on every cache miss, so latency-sensitive and write-heavy workloads benefit from local NVMe SSDs.

The trade-off is durability. If the node fails, the local volume is lost, and the replacement member needs a full initial sync from another member, which can take hours for a large dataset. Size the oplog to cover that time, and keep backups current.

Use the same storage class for every member of a replica set. Any member can become the primary, and secondaries apply the same writes as the primary, so a slow secondary falls behind and becomes a slow primary after the next failover.

Network-attached (EBS)Local NVMe SSD
LatencyAbout 1 msAbout 0.1 ms
ThroughputMediumHigh
Node failureData survives, and the volume re-attaches to the new podData on the node is lost, and the member needs a full initial sync
CostProvisioned IOPS add costBetter cost per IOPS
Best forGeneral workloads and simplicityWrite-heavy, latency-sensitive workloads

4. Monitoring MongoDB on Kubernetes

Kubernetes changes how monitoring works. Pods come and go and their IPs change, so the monitoring stack has to discover targets dynamically. For MongoDB, the usual choices are Prometheus with Percona's mongodb_exporter, or Percona Monitoring and Management (PMM), which builds on the same exporter.

Prometheus, Grafana, and PMM

mongodb_exporter collects serverStatus, replSetGetStatus, and database statistics and exposes them as Prometheus metrics. Run it as a sidecar next to each mongod, and let Prometheus Operator find it through a ServiceMonitor or PodMonitor, so you never hardcode scrape targets.

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
spec:
  selector:
    matchLabels:
      app: mongodb-exporter
  endpoints:
  - port: metrics
    path: /metrics

With the Percona Operator, enabling PMM adds a pmm-client sidecar to every pod. It ships metrics and query data to a PMM server, which comes with MongoDB dashboards and Query Analytics for slow operations.

MongoDB-specific metrics

Generic Kubernetes metrics such as CPU, memory, and network tell you the pod is alive. MongoDB metrics tell you whether the database is healthy. Instrument these five first:

MetricSourceWhat to watch
Replication lagreplSetGetStatus member optimesSeconds each secondary is behind the primary. Alert if lag keeps growing, not on short spikes.
Oplog windowrs.printReplicationInfo(), first and last oplog entriesHours covered by the oplog. Alert when it gets shorter than your longest planned maintenance.
WiredTiger cacheserverStatus().wiredTiger.cacheDirty data above 20% of the cache makes application threads help with eviction, which stalls queries. A rising rate of pages read into the cache means the working set no longer fits.
ConnectionsserverStatus().connectionsEach connection has its own thread and about 1 MB of memory. The total is the driver's maxPoolSize times the number of application pods, so check it when you scale out the app.
Queued operationsserverStatus().globalLock.currentQueueOperations waiting for a read or write ticket. A queue that doesn't drain means the server is saturated.

Adapting monitoring for Kubernetes

  • Use ServiceMonitor or PodMonitor and never hardcode Prometheus scrape targets.
  • Alert on member states other than PRIMARY (1) and SECONDARY (2), such as RECOVERING (3), STARTUP2 (5), UNKNOWN (6), DOWN (8), and ROLLBACK (9).
  • Alert on unexpected elections. Frequent primary changes point to pods being evicted, nodes under pressure, or network problems.
  • For sharded clusters, alert right away if the config server replica set has no primary.
  • Track PVC capacity and alert at around 80%. WiredTiger doesn't give space back to the filesystem after deletes until you compact or resync.
  • Watch slow operations. Operations slower than slowms (100 ms by default) are written to the log, and PMM Query Analytics ranks them.
  • Alert if PBM's point-in-time recovery stops uploading the oplog, as shown by pbm status. A silent gap breaks your recovery window.

5. Backup strategies

Backups are the last line of defence. MongoDB's equivalent of PostgreSQL's WAL is the oplog: with a base backup and a continuous copy of the oplog in object storage, you can recover to any second in your retention window.

Percona Backup for MongoDB (PBM)

Percona Backup for MongoDB is the most widely used open source backup tool for MongoDB on Kubernetes. It runs as a pbm-agent sidecar next to each mongod, writes to S3-compatible storage, Azure Blob Storage, or Google Cloud Storage, and coordinates sharded clusters so that all shards and the config servers are backed up to a consistent point. The Percona Operator drives it through Kubernetes resources for backups and restores.

Keep backups outside the Kubernetes cluster: in a separate account or region, or at the very least a separate namespace. If the cluster is compromised or destroyed, your backups survive.

Backup typeHow it worksUse it for
PhysicalCopies WiredTiger data files using the backup cursor in Percona Server for MongoDB. Fast for large datasets. Restoring stops the database while the files are replaced.Production, especially large datasets
Incremental physicalCopies only the data changed since the previous backup, on top of a full physical base.Very large datasets backed up often
LogicalExports documents, like mongodump. Slower, but restores into a running cluster and can restore single databases or collections.Smaller datasets and selective restores

Point-in-time recovery (oplog archiving)

A base backup is a snapshot of one moment. Real incidents often need a restore to an exact second, such as just before a bad drop() or a faulty migration. With point-in-time recovery enabled, PBM continuously copies the oplog to object storage in small chunks, every 10 minutes by default. A restore loads the base backup, then replays the oplog up to the moment you choose.

You can restore to any second that has been uploaded. If the whole cluster is lost, you can lose at most the last unfinished chunk, so a shorter chunk interval means a smaller recovery point.

Oplog chunks uploaded to S3 every 10 minutesBase backupBase backupMon 00:00Thu 00:00Restore to Wed 14:31orders dropped at Wed 14:32
Recovery restores Monday's base backup, replays the archived oplog chunks, and stops one minute before the orders collection was dropped.

With the Percona Operator, a point-in-time restore is a Kubernetes resource:

apiVersion: psmdb.percona.com/v1
kind: PerconaServerMongoDBRestore
metadata:
  name: before-orders-drop
spec:
  clusterName: production
  backupName: daily-backup-mon
  pitr:
    type: date
    date: "2026-10-21 14:31:00"

Backup architecture decisions

ApproachSetupWhy
RecommendedPBM physical backups with point-in-time recovery, stored in S3 in a separate cloud account or regionFast backups and restores, recovery to any second, and it survives the loss of the cluster. Test restores regularly, because an untested backup is not a backup.
Acceptable for small datasetsPBM logical backups with point-in-time recoverySimpler and allows selective restores, but backups and restores get slow as data grows.
Acceptable for dev and stagingS3-compatible storage such as MinIO, RustFS, or Ceph running in the same Kubernetes clusterConvenient, but it shares the cluster's fate. If you lose the cluster, you lose the backups.
Not recommendedA mongodump cron job, or volume snapshots on their ownNo point-in-time recovery. Snapshots taken shard by shard aren't consistent across a sharded cluster.

6. MongoDB operators compared

There are fewer MongoDB operators than PostgreSQL ones, and they differ most in what is free. Sharding and backups are the features to check first.

OperatorMaintainerLicenseShardingBackups
Percona Operator for MongoDBPerconaApache 2.0YesPBM: physical, logical, and point-in-time recovery
MongoDB Controllers for Kubernetes (MCK)MongoDB, Inc.Apache 2.0. Enterprise features need an Enterprise Advanced subscriptionEnterprise Advanced onlyThrough Ops Manager or Cloud Manager, Enterprise Advanced only
KubeDBAppsCodeProprietaryYesKubeStash
OpenEverestCNCF Sandbox projectApache 2.0YesPBM with point-in-time recovery. A control plane with a UI and API, built on the Percona Operator
Atlas Kubernetes OperatorMongoDB, Inc.Apache 2.0Yes, in AtlasAtlas Cloud Backup. The database runs in Atlas, not in your cluster

Percona Operator for MongoDB

The most complete open source MongoDB operator. It runs Percona Server for MongoDB, a drop-in replacement for MongoDB Community Server that adds features such as LDAP authentication, audit logging, and encryption at rest with HashiCorp Vault or KMIP. It supports replica sets and sharded clusters, PBM backups with point-in-time recovery, PMM monitoring, split horizon, and replication across Kubernetes clusters.

MongoDB Controllers for Kubernetes (MCK)

In 2025, MongoDB, Inc. merged its Community Operator and Enterprise Operator into a single operator, MCK. The old Community Operator repository is now archived. For MongoDB Community Server, MCK manages replica sets, users, custom roles, TLS, and a Prometheus endpoint, but not sharded clusters or backups. Those, along with automation through Ops Manager or Cloud Manager, need a MongoDB Enterprise Advanced subscription.

KubeDB

Part of a multi-database operator suite (PostgreSQL, MySQL, Redis, and others) with one management plane. It supports replica sets and sharded clusters, with backups through KubeStash. It is not open source, and most features need a license. It is convenient if you want one commercial operator for many database types.

Atlas Kubernetes Operator

Manages MongoDB Atlas projects, clusters, and users through Kubernetes resources. The operator is open source, but the database runs in Atlas, not on your Kubernetes nodes. It is a good way to keep Atlas configuration in Git, but it is not a self-hosting option.

OpenEverest

OpenEverest is a CNCF Sandbox project for running databases on Kubernetes through one control plane. Its MongoDB provider is based on the Percona Operator for MongoDB, so you get replica sets and sharded clusters, PBM backups with point-in-time recovery to S3-compatible storage, and PMM monitoring from the same UI and API. An explorer for MongoDB, available as a plugin, lets you browse collections and run queries without leaving the UI.

OpenEverest is modular, so the operator underneath is pluggable. The same approach covers PostgreSQL, MySQL, and a growing list of other databases. You learn one API and one way of operating, whichever operator or database runs underneath.

Related whitepapers

Choosing between self-hosting and a managed service? See Solanica vs MongoDB Atlas.

Run MongoDB on Kubernetes with Solanica

Solanica builds on OpenEverest to give you replica sets, sharded clusters, and point-in-time recovery for MongoDB through one open source control plane, on infrastructure you own. Talk to us about your setup, or try OpenEverest yourself.