Appearance
PostgreSQL
CloudNativePG provides you with an easy way to create and manage PostgreSQL databases inside your Kubernetes cluster.
It is a Kubernetes operator that covers the full lifecycle of highly available, production-ready database clusters with a primary/standby architecture using native streaming replication, automated failovers, backups and Point-In-Time-Recovery.
PostgreSQL is widely considered to be the world's most advanced open-source database. It features transactions with atomicity, consistency, isolation, durability (ACID) properties, automatically updatable views, materialized views, triggers, foreign keys, and stored procedures.
PostgreSQL can be the database of choice for many other non-traditional use cases as well. With its JSONB support for document storage it can replace most NoSQL databases (such as MongoDB), it features PostGIS for geospatial, pg_cron for scheduling, TimescaleDB for time-series, hstore for key-value, and LISTEN/NOTIFY for pub/sub messaging use cases.
PostgreSQL can replace an entire zoo of specialized databases while maintaining ACID guarantees across all of them. Its query planner, write-ahead logging, and mature replication ecosystem give it the reliability and performance characteristics of a purpose-built engine in each of those domains, without the operational overhead of running and synchronizing multiple datastores. For the vast majority of workloads, adding another database to an application stack adds complexity, consistency headaches, and operational burden that can instead be eliminated with PostgreSQL.
Installation
To install the CloudNativePG operator, select it from the list of installable applications for your Kubernetes cluster. Follow this guide on how to get there.
cloudnative-pg
Select the cloudnative-pg application from the list:

Continue to proceed with the application installation steps. Do not change the provided default values.yaml unless necessary.
💡 Note
The shown values will also contain a list of out-of-the-box supported container images for PostgreSQL and PgBouncer that can be used. Take note as these will be needed in later steps if your Kubernetes Service environment is air-gapped.
plugin-barman-cloud
In order for CloudNativePG to be able to provide you with backups, WAL archiving and Point-In-Time-Recovery features it requires the additional plugin-barman-cloud application to also be installed.
💡 Note
While the installation of the barman plugin is entirely optional it is nevertheless good practice and highly recommended to have backups of database clusters!
The installation procedure is the same as for cloudnative-pg, and the result afterwards should look like this:

You can also see the cloudnative-pg and plugin-barman-cloud namespaces where the applications have been installed in your cluster:
bash
kubectl get namespacesNAME STATUS AGE
cert-manager Active 3d
cilium-secrets Active 4d
cloud-init-settings Active 4d
cloudnative-pg Active 17m
default Active 4d
kube-node-lease Active 4d
kube-public Active 4d
kube-system Active 4d
kubernetes-dashboard Active 4d
kubevirt-csi-driver Active 4d
plugin-barman-cloud Active 14mcnpg.io kubectl plugin
Even though everything in CloudNativePG can be managed directly via kubectl in your Kubernetes cluster, it is recommended to install the cnpg kubectl plugin.
While there are many different ways to install the plugin, we generally recommend using krew:
bash
kubectl krew install cnpgConsult the plugin documentation for usage information once installed.
Database management
Create a DB Cluster
Here is a yaml manifest to create an example CloudNativePG PostgreSQL cluster:
yaml
---
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: example-db
namespace: example
spec:
instances: 3
# replace "ENV_ID" with your environment ID:
# https://docs.cloud.swisscom.ch/guide/cloud-services/kubernetes-service/manage/environment/#environment-id
imageName: registry.ENV_ID.ks.private.cloud.swisscom.ch/cloudnative-pg/postgresql:17.7
primaryUpdateStrategy: unsupervised
primaryUpdateMethod: switchover
switchoverDelay: 3600
failoverDelay: 180
inheritedMetadata:
# setup labels that can be used for pod (anti-)affinity
labels:
pg.swisscom.com/cluster: example-db
# set prometheus scraping annotations
annotations:
prometheus.io/path: /metrics
prometheus.io/port: "9187"
prometheus.io/scrape: "true"
# configure anti-affinity to distribute replicas across availability zones
affinity:
enablePodAntiAffinity: true
topologyKey: topology.kubernetes.io/zone
podAntiAffinityType: preferred
additionalPodAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- topologyKey: kubernetes.io/hostname
labelSelector:
matchExpressions:
- key: pg.swisscom.com/cluster
operator: In
values:
- example-db
storage:
size: 20Gi
storageClass: kubevirt-san-kcsi-standard
resources:
requests:
memory: "2Gi"
cpu: "2"
limits:
memory: "4Gi"
cpu: "4"
monitoring:
enablePodMonitor: false # enable if you have the prometheus-operator and PodMonitor CRD
bootstrap: # see https://cloudnative-pg.io/docs/1.28/bootstrap for options
initdb:
database: example-db
owner: example-user
postgresql: # example parameters, see https://cloudnative-pg.io/docs/1.28/postgresql_conf
parameters:
shared_buffers: "256MB"
max_connections: "100"This will deploy a database cluster with 3 PostgreSQL instances: 1 master and 2 standby replicas with streaming replication.
Please consult the CloudNativePG Cluster spec API reference for more details on further possible configuration options.
The result on Kubernetes will be:
bash
kubectl -n example get allNAME READY STATUS RESTARTS AGE
pod/example-db-1 1/1 Running 0 6m13s
pod/example-db-2 1/1 Running 0 3m52s
pod/example-db-3 1/1 Running 0 115s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/example-db-r ClusterIP 10.241.14.116 <none> 5432/TCP 7m29s
service/example-db-ro ClusterIP 10.241.9.106 <none> 5432/TCP 7m29s
service/example-db-rw ClusterIP 10.241.10.121 <none> 5432/TCP 7m29sYou can also use the aforementioned cnpg kubectl plugin to get a more detailed overview of the cluster status:
bash
kubectl cnpg -n example status example-dbCluster Summary
Name example/example-db
System ID: 7640174195310297107
PostgreSQL Image: cloudnative-pg/postgresql:17.7
Primary instance: example-db-1
Primary promotion time: 2026-05-15 17:38:26 +0000 UTC (10m18s)
Status: Cluster in healthy state
Instances: 3
Ready instances: 3
Size: 127M
Current Write LSN: 0/7000000 (Timeline: 1 - WAL File: 000000010000000000000007)
Continuous Backup not configured
Streaming Replication status
Replication Slots Enabled
Name Sent LSN Write LSN Flush LSN Replay LSN Write Lag Flush Lag Replay Lag State Sync State Sync Priority Replication Slot
---- -------- --------- --------- ---------- --------- --------- ---------- ----- ---------- ------------- ----------------
example-db-2 0/7000000 0/7000000 0/7000000 0/7000000 00:00:00 00:00:00 00:00:00 streaming async 0 active
example-db-3 0/7000000 0/7000000 0/7000000 0/7000000 00:00:00 00:00:00 00:00:00 streaming async 0 active
Instances status
Name Current LSN Replication role Status QoS Manager Version Node
---- ----------- ---------------- ------ --- --------------- ----
example-db-1 0/7000000 Primary OK Burstable 1.29.0 olt-769694b688-7wr5t
example-db-2 0/7000000 Standby (async) OK Burstable 1.29.0 zhh-56975dbc85-t622j
example-db-3 0/7000000 Standby (async) OK Burstable 1.29.0 zoi-79d454c67f-9kr78Create a Connection Pool
CloudNativePG includes native support for connection pooling with PgBouncer.
A connection pool in CloudNativePG is a deployment of PgBouncer pods that sit between your applications and the PostgreSQL instance and provide pooled connections to the database.
See the CloudNativePG Connection pooling documentation for a detailed explanation.
yaml
---
apiVersion: postgresql.cnpg.io/v1
kind: Pooler
metadata:
name: example-db-pooler
namespace: example
spec:
instances: 2
cluster:
name: example-db
type: rw
pgbouncer:
poolMode: session
parameters:
# https://cloudnative-pg.io/docs/1.28/connection_pooling#pgbouncer-configuration-options
max_client_conn: "250"
template:
# setup labels that can be used for pod (anti-)affinity
metadata:
labels:
pg.swisscom.com/pooler: example-db
spec:
containers:
- name: pgbouncer
# replace "ENV_ID" with your environment ID:
# https://docs.cloud.swisscom.ch/guide/cloud-services/kubernetes-service/manage/environment/#environment-id
image: registry.ENV_ID.ks.private.cloud.swisscom.ch/cloudnative-pg/pgbouncer:1.24.1
resources:
requests:
cpu: 250m
memory: 128Mi
limits:
cpu: "1"
memory: 512Mi
affinity:
# configure pod affinity to prefer PgBouncer pods being located near the database pods
podAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- podAffinityTerm:
labelSelector:
matchExpressions:
- key: pg.swisscom.com/cluster
operator: In
values:
- example-db
topologyKey: kubernetes.io/hostname
weight: 100
# configure anti-affinity to distribute replicas across availability zones
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- podAffinityTerm:
labelSelector:
matchExpressions:
- key: pg.swisscom.com/pooler
operator: In
values:
- example-db
topologyKey: topology.kubernetes.io/zone
weight: 100
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: pg.swisscom.com/pooler
operator: In
values:
- example-db
topologyKey: kubernetes.io/hostname
monitoring:
enablePodMonitor: false # enable if you have the prometheus-operator and PodMonitor CRDThe above yaml will deploy 2 PgBouncer instances that can be used by clients for connection pooling towards the PostgreSQL database.
Please consult the CloudNativePG Pooler spec API reference for more details on further possible configuration options.
We can see the pooler instances that have been created on Kubernetes, as well as the additional service example-db-pooler. Clients connecting to the database can now use that service to make use of the connection pool instead:
bash
kubectl -n example get allNAME READY STATUS RESTARTS AGE
pod/example-db-1 1/1 Running 0 26m
pod/example-db-2 1/1 Running 0 23m
pod/example-db-3 1/1 Running 0 21m
pod/example-db-pooler-84cfbfc8b9-6cbmh 1/1 Running 0 3m20s
pod/example-db-pooler-84cfbfc8b9-hs9p8 1/1 Running 0 3m20s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/example-db-pooler ClusterIP 10.241.10.77 <none> 5432/TCP 3m20s
service/example-db-r ClusterIP 10.241.14.116 <none> 5432/TCP 27m
service/example-db-ro ClusterIP 10.241.9.106 <none> 5432/TCP 27m
service/example-db-rw ClusterIP 10.241.10.121 <none> 5432/TCP 27m
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/example-db-pooler 2/2 2 2 3m20s
NAME DESIRED CURRENT READY AGE
replicaset.apps/example-db-pooler-84cfbfc8b9 2 2 2 3m20sCredentials and connection string
bash
kubectl -n example get secretsNAME TYPE DATA AGE
example-db-app kubernetes.io/basic-auth 11 34m
example-db-ca Opaque 2 34m
example-db-pooler kubernetes.io/tls 2 11m
example-db-replication kubernetes.io/tls 2 34m
example-db-server kubernetes.io/tls 2 34mWe can see that an example-db-app secret was automatically created. This secret will hold all necessary information for clients to connect to the database.
The contents of this secret will look something like this:
yaml
dbname: example-db
fqdn-jdbc-uri: jdbc:postgresql://example-db-rw.example.svc.cluster.local:5432/example-db?password=61Oing0fsZsXtv7efo4PxhKfP04YFsl0tqtTYaYiqbNNM5Sq9gpeNgYuQiehTOij&user=example-user
fqdn-uri: postgresql://example-user:61Oing0fsZsXtv7efo4PxhKfP04YFsl0tqtTYaYiqbNNM5Sq9gpeNgYuQiehTOij@example-db-rw.example.svc.cluster.local:5432/example-db
host: example-db-rw
jdbc-uri: jdbc:postgresql://example-db-rw.example:5432/example-db?password=61Oing0fsZsXtv7efo4PxhKfP04YFsl0tqtTYaYiqbNNM5Sq9gpeNgYuQiehTOij&user=example-user
password: 61Oing0fsZsXtv7efo4PxhKfP04YFsl0tqtTYaYiqbNNM5Sq9gpeNgYuQiehTOij
pgpass: |
example-db-rw:5432:example-db:example-user:61Oing0fsZsXtv7efo4PxhKfP04YFsl0tqtTYaYiqbNNM5Sq9gpeNgYuQiehTOij
port: "5432"
uri: postgresql://example-user:61Oing0fsZsXtv7efo4PxhKfP04YFsl0tqtTYaYiqbNNM5Sq9gpeNgYuQiehTOij@example-db-rw.example:5432/example-db
user: example-user
username: example-userAll connection strings in the secret point towards the example-db-rw service endpoint by default. These could potentially be changed to example-db-pooler if the client wants to make of use the connection pool created earlier.
See Application Connections documentation for details on all the properties found inside the secret, and SSL Connections if your client applications want to use mTLS/SSL based authentication towards the database instead.
External availability
By default the services created for our example-db are only available internally to the Kubernetes cluster that hosts the database, they are assigned only a clusterIP. This means only applications running on the same Kubernetes cluster can access the database (depending on NetworkPolicies potentially).
However if the database needs to be made available externally to other Kubernetes clusters, remote clients, applications, etc., then we can configure an additional service in the existing cluster definition that will claim a LoadBalancer IP.
bash
kubectl -n example edit cluster/example-dbyaml
...
managed:
services:
additional:
- selectorType: rw
serviceTemplate:
metadata:
name: "example-db-lb"
## uncomment the line below if you want to explicitely specify the LB IP
# annotations:
# metallb.io/loadBalancerIPs: 1.2.3.4
spec:
type: LoadBalancerThis will result creating a new, additional service of type LoadBalancer:
bash
kubectl -n example get svcNAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
example-db-lb LoadBalancer 10.241.12.137 144.11.29.17 5432:30754/TCP 39s
example-db-pooler ClusterIP 10.241.14.250 <none> 5432/TCP 26m
example-db-r ClusterIP 10.241.9.196 <none> 5432/TCP 49m
example-db-ro ClusterIP 10.241.13.80 <none> 5432/TCP 49m
example-db-rw ClusterIP 10.241.3.25 <none> 5432/TCP 49mAs we can see the new example-db-lb service has received an externalIP.
Similar adjustments could also be done to the connection pooler service instead.
bash
kubectl -n example edit pooler/example-db-pooleryaml
...
serviceTemplate:
spec:
type: LoadBalancerNow the pooler service will instead directly receive an externalIP.
See the service management documentation and ServiceTemplateSpec for more details.
⚠️ Use TLS/SSL for external connections
Please be aware that this exposes the database externally. It is advised to at least use TLS/SSL encryption and optionally also server verification when connecting applications to the database by adding either sslmode=require, or sslmode=verify-ca and sslrootcert=/path/to/ca.crt to the connection string. The CA to verify would the one found inside the example-db-ca secret.
Please consult the official Postgres SSL Support documentation for details on these modes.
Backups
Ensure the optional plugin-barman-cloud application has also been installed before proceeding further with this section.
WAL Archiving
To enable WAL archiving (and backups), the cluster needs to be configured with an S3 object store and the barman plugin.
First create a new barman ObjectStore resource:
yaml
---
apiVersion: v1
kind: Secret
metadata:
name: example-db-s3-credentials
namespace: example
type: Opaque
stringData:
ACCESS_KEY_ID: <access-key-id-from-s3-user>
ACCESS_SECRET_KEY: <secret-access-key-from-s3-user>
---
apiVersion: barmancloud.cnpg.io/v1
kind: ObjectStore
metadata:
name: example-db
namespace: example
spec:
configuration:
destinationPath: s3://example-db-bucket/example-db-sub-path
endpointURL: https://ds12s3.swisscom.com
s3Credentials:
accessKeyId:
name: example-db-s3-credentials
key: ACCESS_KEY_ID
secretAccessKey:
name: example-db-s3-credentials
key: ACCESS_SECRET_KEY
wal:
compression: gzip
data:
compression: gzip
retentionPolicy: "30d"Then edit the existing cluster object to enable its use:
bash
kubectl -n example edit cluster/example-dbyaml
...
env: # fixes boto3 / aws-sdk checksum errors with Swisscom S3 Object Storage
- name: AWS_REQUEST_CHECKSUM_CALCULATION
value: when_required
- name: AWS_RESPONSE_CHECKSUM_VALIDATION
value: when_required
backup:
target: prefer-standby
plugins:
- name: barman-cloud.cloudnative-pg.io
isWALArchiver: true
parameters:
barmanObjectName: example-dbOnce these values are set, the cluster will automatically start to archive WAL files onto the S3 object store.
Create Backups
Once the barman plugin has been enabled by the steps mentioned above, we can then also configure CloudNativePG to create base backups of the cluster and store them onto the S3 object store.
Backups can either be triggered on-demand with the cnpg kubectl plugin, or they can be scheduled to run periodically.
To run an on-demand backup:
bash
kubectl cnpg -n example backup example-db \
--method plugin --plugin-name "barman-cloud.cloudnative-pg.io" \
--plugin-parameters "barmanObjectName=example-db"This will then create a new physical base backup.
Confirm its existence with:
bash
kubectl -n example get backups.postgresql.cnpg.ioNAME AGE CLUSTER METHOD PHASE ERROR
example-db-20260515182900 3m example-db plugin completedScheduled backups
Backups can also be configured to run periodically, by defining a cron schedule.
Create a new ScheduledBackup object to define an automatic periodical backup:
yaml
---
apiVersion: postgresql.cnpg.io/v1
kind: ScheduledBackup
metadata:
name: example-db
namespace: example
spec:
cluster:
name: example-db
schedule: "0 33 03 * * *"
backupOwnerReference: self
method: plugin
pluginConfiguration:
name: barman-cloud.cloudnative-pg.io
immediate: true # creates an initial base backup immediatelyPlease consult the Backup documentation for more details on various backup methods and configuration options.
Verify backup and WAL archiving status
Once all of these values are set, the cluster is configured to archive WAL files onto the S3 object store and automatically create base backups on a daily basis. This can be verified by using the cnpg kubectl plugin for example:
bash
kubectl cnpg -n example status example-dbCluster Summary
Name example/example-db
System ID: 7640174195310297107
PostgreSQL Image: cloudnative-pg/postgresql:17.7
Primary instance: example-db-1
Primary promotion time: 2026-05-15 18:11:19 +0000 UTC (1h21m38s)
Status: Cluster in healthy state
Instances: 3
Ready instances: 3
Size: 219M
Current Write LSN: 231/F6E7D10 (Timeline: 17 - WAL File: 00000025000002310000000F)
Continuous Backup status (Barman Cloud Plugin)
ObjectStore / Server name: example-db/example-db
First Point of Recoverability: 2026-05-15 18:11:19 CEST
Last Successful Backup: 2026-05-15 18:13:22 CEST
Last Failed Backup: -
Working WAL archiving: OK
WALs waiting to be archived: 0
Last Archived WAL: 000000250000023100000010 @ 2026-05-15T18:19:32.953342Z
Streaming Replication status
Replication Slots Enabled
Name Sent LSN Write LSN Flush LSN Replay LSN Write Lag Flush Lag Replay Lag State Sync State Sync Priority Replication Slot
---- -------- --------- --------- ---------- --------- --------- ---------- ----- ---------- ------------- ----------------
example-db-2 231/F6E7D10 231/F6E7D10 231/F6E7D10 231/F6E7D10 00:00:00.002477 00:00:00.005731 00:00:00.005738 streaming async 0 active
example-db-3 231/F6E7D10 231/F6E7D10 231/F6E7D10 231/F6E7D10 00:00:00.001301 00:00:00.003886 00:00:00.003894 streaming async 0 active
Instances status
Name Current LSN Replication role Status QoS Manager Version Node
---- ----------- ---------------- ------ --- --------------- ----
example-db-1 231/F6E7D10 Primary OK Burstable 1.29.0 olt-769694b688-7wr5t
example-db-2 231/F6E7D10 Standby (async) OK Burstable 1.29.0 zhh-56975dbc85-t622j
example-db-3 231/F6E7D10 Standby (async) OK Burstable 1.29.0 zoi-79d454c67f-9kr78
Plugins status
Name Version Status Reported Operator Capabilities
---- ------- ------ ------------------------------
barman-cloud.cloudnative-pg.io 0.12.0 N/A Reconciler Hooks, Lifecycle Service, TYPE_INSTANCE_SIDECAR_INJECTIONWe can see it shows Continuous Backup status.
Recovery
In CloudNativePG recovery is not performed in-place on an existing cluster. Instead it is used to bootstrap a new cluster from a physical base backup. For this the user has to create a new Cluster resource that references the backup data from the S3 object store.
A valid WAL archive is required to perform Point-In-Time-Recovery (PITR).
Restore from the latest backup
To restore a new cluster from the latest available backup, create a new Cluster that uses the recovery bootstrap method and references the existing ObjectStore:
yaml
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: example-db-restore
namespace: example
spec:
instances: 3
# replace "ENV_ID" with your environment ID:
# https://docs.cloud.swisscom.ch/guide/cloud-services/kubernetes-service/manage/environment/#environment-id
imageName: registry.ENV_ID.ks.private.cloud.swisscom.ch/cloudnative-pg/postgresql:17.7
storage:
size: 20Gi
storageClass: kubevirt-san-kcsi-standard
bootstrap:
recovery:
source: origin
externalClusters:
- name: origin
plugin:
name: barman-cloud.cloudnative-pg.io
parameters:
barmanObjectName: example-db
serverName: example-dbThis will restore the new cluster from the latest base backup and replay all available WAL files up to the most recent archived segment.
Point-In-Time-Recovery (PITR)
Instead of replaying all WALs up to the latest one, you can ask PostgreSQL to stop replaying at any given point in time to perform a Point-In-Time-Recovery (PITR). As the name suggests this allows you to recover the database to a specific moment in time, for example right before an accidental data deletion.
Add a recoveryTarget with a targetTime to the recovery configuration:
yaml
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: example-db-pitr
namespace: example
spec:
instances: 3
# replace "ENV_ID" with your environment ID:
# https://docs.cloud.swisscom.ch/guide/cloud-services/kubernetes-service/manage/environment/#environment-id
imageName: registry.ENV_ID.ks.private.cloud.swisscom.ch/cloudnative-pg/postgresql:17.7
storage:
size: 20Gi
storageClass: kubevirt-san-kcsi-standard
bootstrap:
recovery:
source: origin
recoveryTarget:
targetTime: "2026-05-15T19:14:21+02:00"
externalClusters:
- name: origin
plugin:
name: barman-cloud.cloudnative-pg.io
parameters:
barmanObjectName: example-db
serverName: example-dbThe targetTime must be expressed as a timestamp with an explicit timezone suffix. The operator will automatically select the closest base backup that was completed before the specified target time and replay WALs up to that point.
⚠️ Important
Make sure the serverName in the externalClusters section matches the original cluster name that produced the backups. Do not reuse the same ObjectStore for both backup and recovery in the same cluster as this could lead to data overwrites.
Please consult the CloudNativePG Recovery documentation for more details on additional recovery targets (targetLSN, targetXID, targetName) and other advanced recovery options.
