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.
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:
- 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.
- Operations are automated. Operators handle provisioning, rolling upgrades, scaling, TLS certificates, and backups through Kubernetes resources instead of runbooks.
- 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=rs0Inside 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.
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.
| Mode | Where reads go |
|---|---|
primary | Always the primary. The default, with the strongest consistency. |
primaryPreferred | The primary, or a secondary if no primary is available. |
secondary | Only secondaries. Useful for analytics that shouldn't load the primary. |
secondaryPreferred | Secondaries, or the primary if no secondary is available. |
nearest | The 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/zoneConnecting 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.
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: 3Choosing 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 key | Result |
|---|---|
{ 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 class | When a pod gets it |
|---|---|
| Guaranteed | Requests equal limits |
| Burstable | Requests lower than limits |
| BestEffort | No 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.5Plain mongod: 0.5 × (16 − 1) GB.
replsets:
- name: rs0
storage:
wiredTiger:
engineConfig:
cacheSizeRatio: 0.5Percona 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 megabytesCheck 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 | |
|---|---|---|
| Latency | About 1 ms | About 0.1 ms |
| Throughput | Medium | High |
| Node failure | Data survives, and the volume re-attaches to the new pod | Data on the node is lost, and the member needs a full initial sync |
| Cost | Provisioned IOPS add cost | Better cost per IOPS |
| Best for | General workloads and simplicity | Write-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: /metricsWith 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:
| Metric | Source | What to watch |
|---|---|---|
| Replication lag | replSetGetStatus member optimes | Seconds each secondary is behind the primary. Alert if lag keeps growing, not on short spikes. |
| Oplog window | rs.printReplicationInfo(), first and last oplog entries | Hours covered by the oplog. Alert when it gets shorter than your longest planned maintenance. |
| WiredTiger cache | serverStatus().wiredTiger.cache | Dirty 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. |
| Connections | serverStatus().connections | Each 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 operations | serverStatus().globalLock.currentQueue | Operations waiting for a read or write ticket. A queue that doesn't drain means the server is saturated. |
Adapting monitoring for Kubernetes
- Use
ServiceMonitororPodMonitorand 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 type | How it works | Use it for |
|---|---|---|
| Physical | Copies 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 physical | Copies only the data changed since the previous backup, on top of a full physical base. | Very large datasets backed up often |
| Logical | Exports 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.
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
| Approach | Setup | Why |
|---|---|---|
| Recommended | PBM physical backups with point-in-time recovery, stored in S3 in a separate cloud account or region | Fast 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 datasets | PBM logical backups with point-in-time recovery | Simpler and allows selective restores, but backups and restores get slow as data grows. |
| Acceptable for dev and staging | S3-compatible storage such as MinIO, RustFS, or Ceph running in the same Kubernetes cluster | Convenient, but it shares the cluster's fate. If you lose the cluster, you lose the backups. |
| Not recommended | A mongodump cron job, or volume snapshots on their own | No 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.
| Operator | Maintainer | License | Sharding | Backups |
|---|---|---|---|---|
| Percona Operator for MongoDB | Percona | Apache 2.0 | Yes | PBM: physical, logical, and point-in-time recovery |
| MongoDB Controllers for Kubernetes (MCK) | MongoDB, Inc. | Apache 2.0. Enterprise features need an Enterprise Advanced subscription | Enterprise Advanced only | Through Ops Manager or Cloud Manager, Enterprise Advanced only |
| KubeDB | AppsCode | Proprietary | Yes | KubeStash |
| OpenEverest | CNCF Sandbox project | Apache 2.0 | Yes | PBM with point-in-time recovery. A control plane with a UI and API, built on the Percona Operator |
| Atlas Kubernetes Operator | MongoDB, Inc. | Apache 2.0 | Yes, in Atlas | Atlas 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
- The Cloud-Native Data Manual: storage, compute, FinOps, security, and availability for production databases on Kubernetes.
- Running PostgreSQL on Kubernetes: streaming replication, Patroni HA, PgBouncer, pgBackRest backups, and operator comparison.
- Running MySQL on Kubernetes: InnoDB Cluster, Group Replication, XtraBackup, and operator selection.
- Running SQL Server on Kubernetes: availability groups without a Windows cluster, memory and licensing-aware sizing, native backups to S3, and operator comparison.
- Running Valkey on Kubernetes: replication and Valkey Cluster, the persistence trap, maxmemory and container limits, RDB and AOF, and operator comparison.
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.