Home›Learn›PostgreSQL on Kubernetes: CloudNativePG
PostgreSQL · High availability · Kubernetes

High availability on Kubernetes: CloudNativePG

What does Kubernetes need to know before it can run a database that fails over by itself?

CloudNativePG is an operator: a controller that keeps a PostgreSQL cluster in the state you declared, and handles failover, switchover, updates and backups.

Why this tool exists

Why run Postgres with an operator on Kubernetes

Kubernetes is good at restarting stateless pods. A database is not stateless. If you run Postgres as a plain StatefulSet, Kubernetes will restart a dead pod, but it knows nothing about replication: which pod is the primary, which replica is furthest ahead, which old primary must not come back as a primary. CloudNativePG (CNPG) is an operator that teaches Kubernetes those rules.

What we are protecting

Writes to one PostgreSQL primary, and the data behind it, while pods, nodes and zones come and go.

What we achieve

Automated failover and switchover, rolling updates that do the primary last, backups to object storage, and one YAML file that describes the whole cluster.

A different design from Patroni

Most Postgres operators run an external failover tool such as Patroni. CNPG's FAQ says it relies on the Kubernetes API server as "the only source of truth" and does not rely on StatefulSets. See the Patroni chapter for the other design.

What it is not

Not a backup by itself, and not cross-cluster failover. The docs say CNPG cannot do automated failover across Kubernetes clusters. Each operator manages its own cluster.

How companies use it

Pinned versions on this page: CloudNativePG 1.30.2 and PostgreSQL 18. Check the supported releases page of the CNPG docs for the Kubernetes versions it supports.

How it was done before

Postgres on Kubernetes without an operator

The first try is a StatefulSet with one primary pod and two replicas, plus a Service that selects the primary by label. It runs. Then the primary pod dies on a node that is gone for good.

  1. Kubernetes cannot reschedule the pod while its volume is stuck on the lost node, or it starts a new empty one. Either way writes are down.
  2. You find the replica that is furthest ahead: SELECT pg_last_wal_replay_lsn(); on each.
  3. You promote it: SELECT pg_promote();.
  4. You edit the Service selector so writes reach it.
  5. You change primary_conninfo on the other replica and reload.
  6. The old primary must not return as a primary. You rewind it with pg_rewind or re-clone it, then add it back.

Patroni solves this inside the pods, with a distributed store (etcd or the Kubernetes API) holding the leader key. It works well and is covered in the Patroni chapter. CNPG moves the same decisions into one Kubernetes controller.

Step through it:

Explained clearly

What CloudNativePG does

1

The problem

You want one object that says "three PostgreSQL instances, this storage, these backups", and a controller that keeps it true when pods, nodes and disks fail.

2

What it is

You install the operator once per Kubernetes cluster. Then you create a Cluster resource (apiVersion: postgresql.cnpg.io/v1). The operator creates a PVC and a pod per instance, and manages the pods and volumes directly instead of through a StatefulSet. Inside each pod, an instance manager runs as PID 1, starts Postgres and serves the health probes.

3

Follow one request

  1. The app connects to the Service CLUSTER-rw.
  2. The Service points at the pod that is the primary right now.
  3. On failover the operator promotes a replica and moves -rw to it.
  4. The app reconnects to the same name and lands on the new primary.
4

What to watch

  • The operator is a single deployment. If it is down, running databases keep running, but nobody fails over or heals them.
  • Storage matters: local disks tie a replica to a node, and CNPG expects instances in different zones and on different nodes.
  • Your app must retry. A failover drops connections.
ServicePoints toUse it for
CLUSTER-rwThe primaryAll writes, and reads that must be current.
CLUSTER-roHot standby replicas onlyRead-only traffic that can be a little behind.
CLUSTER-rAny instanceRead-only traffic when the primary may serve it too.

Step through it:

Step by step

Set it up

Pinned: CloudNativePG 1.30.2, PostgreSQL 18, three instances. You need a Kubernetes cluster with at least three nodes in different zones and a StorageClass.

  1. Install the operator (the command from the 1.30 install page):
kubectl apply --server-side -f \
  https://raw.githubusercontent.com/cloudnative-pg/cloudnative-pg/release-1.30/releases/cnpg-1.30.2.yaml
kubectl rollout status deployment -n cnpg-system cnpg-controller-manager

Helm installs name the deployment cnpg-cloudnative-pg instead.

  1. Create the cluster. Save as orders.yaml:
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: orders
  namespace: db
spec:
  instances: 3
  imageName: ghcr.io/cloudnative-pg/postgresql:18   # pin an exact tag in production
  storage:
    size: 20Gi
  postgresql:
    synchronous:
      method: any
      number: 1
      failoverQuorum: true
  primaryUpdateStrategy: unsupervised
  primaryUpdateMethod: switchover
  affinity:
    enablePodAntiAffinity: true
    topologyKey: topology.kubernetes.io/zone

failoverQuorum: true makes the operator check, before it promotes, that the replica it picks cannot be missing a synchronous commit. If the check fails, no replica is promoted. primaryUpdateMethod: switchover makes rolling updates move the primary to the best replica. The default is restart, which restarts the primary pod in place when it can.

  1. Apply and check:
kubectl create namespace db
kubectl apply -f orders.yaml
kubectl krew install cnpg          # the cnpg plugin, once
kubectl cnpg status orders -n db
kubectl get cluster -n db
  1. Back up to object storage with the Barman Cloud plugin. Install the plugin per its docs, then create the store and point the cluster at it:
apiVersion: barmancloud.cnpg.io/v1
kind: ObjectStore
metadata:
  name: s3-store
  namespace: db
spec:
  configuration:
    destinationPath: s3://my-backups/orders/
    s3Credentials:
      accessKeyId:     {name: s3-creds, key: ACCESS_KEY_ID}
      secretAccessKey: {name: s3-creds, key: ACCESS_SECRET_KEY}
    wal:
      compression: gzip
---
# add to the Cluster spec
  plugins:
  - name: barman-cloud.cloudnative-pg.io
    isWALArchiver: true
    parameters:
      barmanObjectName: s3-store
apiVersion: postgresql.cnpg.io/v1
kind: Backup
metadata:
  name: orders-first
  namespace: db
spec:
  cluster:
    name: orders
  method: plugin
  pluginConfiguration:
    name: barman-cloud.cloudnative-pg.io

To restore, create a new Cluster with bootstrap.recovery.source set to an externalClusters entry that uses the same plugin, barmanObjectName and the original serverName. Restoring to a new cluster name is how you test a backup without touching production.

Connect with the app secret and the -rw service: orders-rw.db.svc. CNPG creates an application user and secret for you; read the secret names from kubectl get secret -n db.

When it breaks

A primary failure, step by step

Three instances, failoverDelay at its default of 0 seconds. The primary pod's disk fails.

Step through it:

Planned work uses a switchover, not a failure. kubectl cnpg promote orders orders-2 -n db moves the primary to a chosen instance. Rolling updates do replicas first, one pod at a time, and the primary last. With primaryUpdateStrategy: supervised the update pauses after the replicas so you finish it with promote or restart.

Kubernetes timing matters too. The docs mention the node monitor grace period (40 seconds on Kubernetes 1.29 to 1.31, 50 seconds on 1.32 and later) and a default 300 second pod eviction toleration, and say the operator does not wait for eviction to promote. The primary lease defaults are 15 seconds lease duration, 10 renew deadline and 2 retry period. So a failure with a sudden node loss can take longer than a clean pod delete. Measure it on your own cluster before you give it an RTO.

Day to day

The commands you will actually run

These use the kubectl cnpg plugin and plain kubectl. CLUSTER is the Cluster name.

kubectl cnpg status CLUSTER -n NS                 # summary, replication, backup, instance health; add -v for more
kubectl cnpg promote CLUSTER INSTANCE -n NS          # planned switchover to that instance (pod name or number)
kubectl cnpg restart CLUSTER -n NS                   # rolling restart; primary last
kubectl cnpg restart CLUSTER INSTANCE -n NS          # restart one instance (a replica pod is deleted and recreated)
kubectl cnpg reload CLUSTER -n NS                    # run a reconcile loop to pick up dependent config
kubectl cnpg backup CLUSTER -n NS                    # create a Backup resource (on demand)
kubectl cnpg psql CLUSTER -n NS -- -c "select 1"     # psql on the primary; add --replica for a replica
kubectl cnpg report cluster CLUSTER -n NS -f out.zip # bundle resources, events and (with --logs) logs for support
kubectl cnpg maintenance set CLUSTER -n NS --reusePVC   # node drain window; use unset to end it

Fencing and hibernation (not a pause)

kubectl cnpg fencing on CLUSTER INSTANCE_NUMBER -n NS   # stop postgres in that pod, keep the pod; not ready
kubectl cnpg fencing on CLUSTER "*" -n NS                # fence the whole cluster
kubectl cnpg fencing off CLUSTER "*" -n NS
kubectl cnpg hibernate on CLUSTER -n NS                  # stop the cluster and keep the data
kubectl cnpg hibernate off CLUSTER -n NS

Fencing a primary stops Postgres and does not fail over, so apps see an outage. Fence a primary only when you must. Hibernation sets the cnpg.io/hibernation=on annotation. Neither one is the same as pausing the operator, and the agent does not offer a pause for CNPG.

Rejoin and repair

There is no manual rejoin step for a normal case: a failed instance is recreated and rejoins as a replica. If a pod is stuck in a crash loop, fence it, fix the cause, then unfence it. Deleting a fenced pod recreates it with the postmaster not started, which helps with CrashLoopBackOff.

kubectl get pods -n NS -l cnpg.io/cluster=CLUSTER
kubectl describe cluster CLUSTER -n NS
kubectl logs -n NS POD -c postgres
What goes wrong

Failures to plan for

SymptomLikely causeFirst checkFix
Failover does not happen after the primary diesfailoverQuorum blocked it, no healthy replica, or the lease has not expired yet.kubectl cnpg status, describe cluster, operator logs in cnpg-system.Wait for the lease, restore a replica, or as a last resort kubectl cnpg promote, which can lose data. The docs call it a last resort.
Cluster stuck during updateSupervised strategy waiting for you, or a replica not ready.Cluster status phase, pod readiness.Finish with promote or restart. For image changes you need a switchover.
Replica far behindSlow disk, long query, network, or WAL not retained.status -v replication section.Fix the bottleneck. A replica that cannot catch up is re-cloned from the primary.
Backups fail or WAL archive lagsBad credentials, bucket permissions, plugin not installed or not running.Backup resource status, status backup section, plugin pod logs.Fix the secret or policy. An archive that is behind grows WAL on the primary's disk.
Primary disk fillsWAL kept for a broken archive or a stuck replication slot.Disk use on the PVC.Fix archiving, then grow the PVC if your StorageClass allows it.
App sees errors during failoverConnections to the old primary drop.App logs, pool settings.Retry with backoff and use the -rw name. A pooler such as PgBouncer (CNPG has a Pooler resource) can hold connections, but the app still retries.
Operator downDeployment crash, bad upgrade, RBAC.kubectl get deploy -n cnpg-systemDatabases keep running. Restore the operator before you need a failover.
Nodes lost in one zoneInstances were not spread across zones.Pod placement.Use anti-affinity across zones, and three or more instances.
Monitoring

What to watch, and from where

CNPG exposes a Prometheus metrics endpoint on each instance. The docs name one metric you can rely on for fencing, cnpg_collector_fencing_on, which is 1 while a pod is fenced. For the rest, scrape the instance pods and the operator, and start from the dashboards and alert rules that the project publishes.

SignalWhereAlert when
Cluster phase and ready instanceskubectl cnpg status, kube-state-metrics on the Cluster resourceNot all instances ready for more than a few minutes.
Failover and switchover eventsKubernetes events on the ClusterAny failover.
Replication lag, WAL receiver statePostgres metrics on each instanceLag above your RPO.
WAL archive status, last backup timePlugin and Backup resourcesNo successful backup in your window, archive failing.
cnpg_collector_fencing_onInstance metricsAny instance fenced longer than planned.
PVC usekubelet and storage metricsAbove 80 percent.
Operator healthcnpg-system deploymentNot running.

See also Patroni, Something is slow or broken and, for fleets, 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 cnpg --name CLUSTER -n NAMESPACE
python3 -m dbagent.ha k8s switchover --kind cnpg --name CLUSTER --to POD
python3 -m dbagent.ha k8s restart --kind cnpg --name CLUSTER

switchover is a planned move of the primary. restart is the rolling restart. There is no pause for CNPG: hibernation and fencing are different things, and the docs describe no operator pause, so the agent does not offer one.

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