Video Thumbnail for Lesson
9.1: CloudNativePG

CloudNativePG

CloudNativePG is an operator that simplifies running PostgreSQL on Kubernetes. Instead of managing StatefulSets or relying only on a managed database service, we can declare a Cluster resource and let the operator handle replication, failover and backups.

Why use an operator?

  • Declarative management of Postgres clusters
  • Handles replica pods and promotes a new primary when needed
  • Provides CRDs for creating backups on a schedule

Other options are keeping the database outside the cluster or maintaining your own StatefulSet/Helm chart. Using an operator offloads much of the operational logic.

Installing CloudNativePG

The companion repository contains sample Taskfiles in 09-deploying-auxiliary-tooling/cloudnative-pg. Install the operator with Helm:

helm repo add cnpg https://cloudnative-pg.github.io/charts
helm upgrade --install cnpg \
  --namespace cnpg-system \
  --create-namespace \
  cnpg/cloudnative-pg

This installs several CRDs such as Cluster, Backup and ScheduledBackup.

Deploying a cluster

A minimal manifest looks like:

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: cnpg-minimal
spec:
  instances: 2
  storage:
    size: 1Gi

Apply it with kubectl apply -f Cluster.cnpg-minimal.yaml. The operator creates pods for a primary and replica along with services for read/write and read‑only traffic. CloudNativePG manages pods directly instead of StatefulSets.

Backups to object storage

CloudNativePG can store backups in S3 compatible buckets. The repo shows examples for Google Cloud Storage and Civo. Below is a snippet using Workload Identity on GKE:

backup:
  barmanObjectStore:
    destinationPath: "gs://<your-bucket>"
    googleCredentials:
      gkeEnvironment: true
  retentionPolicy: "30d"
serviceAccountTemplate:
  metadata:
    annotations:
      iam.gke.io/gcp-service-account: <gcp-sa>@<project>.iam.gserviceaccount.com

Create a ScheduledBackup to run periodically and you can trigger a backup immediately with the Backup resource. Verify the files appear in your bucket.


For full examples see the cloudnative-pg directory in the companion repository.