> For the complete documentation index, see [llms.txt](https://developer.harness.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.harness.io/self-managed-enterprise-edition/use-self-managed-enterprise-edition/advanced-configuration/external-db/postgresql/use-cloudnativepg-for-postgresql.md).

# Use CloudNativePG as your external PostgreSQL database

Run the Harness Self-Managed Enterprise Edition PostgreSQL database on Kubernetes with CloudNativePG, including migration, backups, and point-in-time recovery.

Use [CloudNativePG](https://cloudnative-pg.io/) (CNPG) to run the Harness Self-Managed Enterprise Edition PostgreSQL database as a highly available cluster on Kubernetes. CNPG handles failover, replication, backups, and point-in-time recovery.

This page uses the community `cluster` Helm chart. Go to [Use an external self-managed PostgreSQL database with your installation](https://developer.harness.io/self-managed-enterprise-edition/use-self-managed-enterprise-edition/advanced-configuration/external-db/postgresql/use-an-external-postgres-database.md) if you run PostgreSQL on virtual machines instead.

{% hint style="info" %}
**Tested on Google Cloud only**

Harness tested this CNPG installation on Google Cloud (GKE and Google Cloud Storage), and the steps on this page are for that platform. To install on another cloud provider, go to the [CloudNativePG documentation](https://cloudnative-pg.io/documentation/current/) and the [Barman Cloud plugin object store documentation](https://cloudnative-pg.io/plugin-barman-cloud/docs/object_stores/) for your provider.
{% endhint %}

## What you will learn from this topic

* How to install a new CNPG cluster for Harness.
* How to migrate an existing PostgreSQL database with minimal downtime.
* How to enable backups to Google Cloud Storage.
* How to restore a backup to a specific point in time.

## Before you begin

* **Kubernetes:** Version 1.29 or later.
* **Tools:** `helm`, `kubectl`, and `yq` version 4.
* **PostgreSQL version:** 16.
* **Extensions:** `pg_partman`, `pg_cron`, and `hstore`.
* **Backups only:** cert-manager, a Google Cloud Storage bucket, and volume snapshot support. Go to [Check volume snapshot requirements](#check-volume-snapshot-requirements) to review the requirements.

{% hint style="info" %}
**Use the Harness PostgreSQL image**

Harness requires the `pg_cron` and `pg_partman` libraries. The standard CNPG images do not include them, so a cluster that uses a standard image fails Harness database setup.

Use `docker.io/harnesssecure/cnpg-postgres:16.14-bookworm`. The image also includes `pgvector` and `pgaudit`.
{% endhint %}

## Architecture

Harness services connect to the primary instance. CNPG streams changes to a replica, archives write-ahead log (WAL) files to object storage, and takes a daily volume snapshot from the replica.

```mermaid
flowchart LR
  A[Harness services] -->|harness-pg-rw| B[(Primary)]
  B -->|streaming replication| C[(Replica)]
  B -->|WAL archive| D[(Object storage)]
  C -->|daily snapshot| E[(Volume snapshot)]
```

Backup and recovery use two parts:

* **Base backups:** A scheduled backup takes a volume snapshot of the replica data volume every day.
* **WAL archive:** CNPG continuously archives WAL files to a Google Cloud Storage bucket through the Barman Cloud plugin.

To recover, CNPG restores a snapshot, then replays the archived WAL files up to the point in time that you choose. This is point-in-time recovery (PITR).

## Install the operator and plugin

Install the CNPG operator. Go to [CloudNativePG installation](https://cloudnative-pg.io/documentation/current/installation_upgrade/) to review all installation options.

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

If you enable backups, install the Barman Cloud plugin. Go to [Barman Cloud plugin installation](https://cloudnative-pg.io/plugin-barman-cloud/docs/installation/) to review the requirements.

```bash
helm upgrade --install plugin-barman-cloud cnpg/plugin-barman-cloud -n cnpg-system
```

## Create the values file

Every procedure on this page uses this file. Replace `<storage-class>` with a storage class in your cluster.

{% code title="pg-values.yaml" overflow="wrap" %}

```yaml
type: postgresql
version:
  postgresql: "16"
fullnameOverride: harness-pg

cluster:
  instances: 2
  annotations:
    helm.sh/resource-policy: keep
  imageName: docker.io/harnesssecure/cnpg-postgres:16.14-bookworm
  storage:
    size: 100Gi
    storageClass: <storage-class>
  enableSuperuserAccess: true
  superuserSecret: harness-pg-superuser
  resources:
    requests: { cpu: "2", memory: 4Gi }
    limits: { cpu: "2", memory: 4Gi }
  postgresql:
    shared_preload_libraries: [pgaudit, pg_cron]
    parameters:
      max_connections: "200"
      max_wal_senders: "16"
      shared_buffers: "1GB"
      wal_level: "logical"
      max_slot_wal_keep_size: "10GB"
      cron.database_name: "postgres"
      cron.use_background_workers: "on"
      pgaudit.log_catalog: "off"
      archive_timeout: "300"
  affinity:
    topologyKey: topology.kubernetes.io/zone
  enablePDB: true
  monitoring:
    enabled: false
  initdb:
    database: postgres
    owner: postgres
    secret:
      name: harness-pg-superuser
    postInitSQL:
      - CREATE EXTENSION IF NOT EXISTS pg_cron
      - CREATE DATABASE harness OWNER postgres
      - CREATE DATABASE harnessti OWNER postgres
      - CREATE DATABASE harness_gitops OWNER postgres
      - SELECT cron.schedule_in_database('harness_partman_run_maintenance', '0 1 * * *', 'select partman.run_maintenance()', 'harness')
      - SELECT cron.schedule_in_database('harnessti_partman_run_maintenance', '0 1 * * *', 'select partman.run_maintenance()', 'harnessti')
      - SELECT cron.schedule_in_database('harness_gitops_partman_run_maintenance', '0 1 * * *', 'select partman.run_maintenance()', 'harness_gitops')

databases:
  - { name: harness, owner: postgres }
  - { name: harnessti, owner: postgres }
  - { name: harness_gitops, owner: postgres }
  - { name: harnesscf, owner: postgres }
  - { name: iro_db, owner: postgres }
```

{% endcode %}

The `helm.sh/resource-policy: keep` annotation keeps the cluster and its volumes if you uninstall the Helm release. The `initdb` settings apply only when CNPG creates a new cluster. The `database`, `owner`, and `secret` settings stop CNPG from creating a separate `app` database and user.

## Install a new cluster

Use this procedure for a new Harness installation that has no existing PostgreSQL data.

{% stepper %}
{% step %}
**Create the superuser secret.** Create the secret in the database namespace and in the Harness namespace. A secret can be read only from its own namespace: CNPG reads it in `cnpg-system`, and the Harness pods read it in the Harness namespace.

```bash
kubectl -n cnpg-system create secret generic harness-pg-superuser \
  --type=kubernetes.io/basic-auth \
  --from-literal=username=postgres --from-literal=password='<password>'
kubectl -n <harness-namespace> create secret generic harness-pg-superuser \
  --type=kubernetes.io/basic-auth \
  --from-literal=username=postgres --from-literal=password='<password>'
```

{% endstep %}

{% step %}
**Install the cluster.**

```bash
helm upgrade --install harness-pg cnpg/cluster --version 0.9.0 -n cnpg-system \
  -f pg-values.yaml
kubectl -n cnpg-system get cluster harness-pg
```

The primary is available at `harness-pg-rw.cnpg-system.svc.cluster.local:5432`.
{% endstep %}

{% step %}
Go to [Connect Harness to PostgreSQL](#connect-harness-to-postgresql) to point Harness at the new cluster.
{% endstep %}
{% endstepper %}

## Migrate an existing PostgreSQL database

Use this procedure to move the PostgreSQL database that ships with Harness to CNPG. The new cluster starts as a streaming replica of your current database, so downtime is limited to the cutover.

{% stepper %}
{% step %}
**Allow replication on the current database.** Add these values to your Harness release, then run `helm upgrade`. This restarts the bundled PostgreSQL once.

```yaml
platform:
  bootstrap:
    database:
      postgresql:
        primary:
          pgHbaConfiguration: |-
            host    replication     postgres        <pod-cidr>            md5
          configuration: |-
            wal_keep_size = 8GB
```

Replace `<pod-cidr>` with the pod CIDR of your cluster. Set `wal_keep_size` to at least the amount of WAL written while the copy runs.
{% endstep %}

{% step %}
**Create the secrets.** The copy uses the existing `postgres` secret to connect to the current database.

```bash
PW="$(kubectl -n <harness-namespace> get secret postgres -o jsonpath='{.data.postgres-password}' | base64 -d)"
kubectl -n cnpg-system create secret generic postgres --from-literal=postgres-password="$PW"
kubectl -n cnpg-system create secret generic harness-pg-superuser \
  --type=kubernetes.io/basic-auth \
  --from-literal=username=postgres --from-literal=password="$PW"
kubectl -n <harness-namespace> create secret generic harness-pg-superuser \
  --type=kubernetes.io/basic-auth \
  --from-literal=username=postgres --from-literal=password="$PW"
unset PW
```

{% endstep %}

{% step %}
**Start the replica cluster.** Create the migration values, then install the cluster.

{% code title="pg-migrate.yaml" overflow="wrap" %}

```yaml
mode: replica
cluster:
  instances: 1
replica:
  bootstrap:
    source: pg_basebackup
  origin:
    pg_basebackup:
      host: postgres.<harness-namespace>.svc.cluster.local
      port: 5432
      username: postgres
      database: postgres
      sslMode: prefer
      passwordSecret:
        create: false
        name: postgres
        key: postgres-password
```

{% endcode %}

```bash
helm upgrade --install harness-pg cnpg/cluster --version 0.9.0 -n cnpg-system \
  -f pg-values.yaml -f pg-migrate.yaml
kubectl -n cnpg-system get cluster harness-pg -w
```

Wait for `Cluster in healthy state`. All databases, roles, and `pg_cron` jobs are copied.
{% endstep %}

{% step %}
**Stop Harness and confirm the new cluster is caught up.** Scale Harness down, then compare the write positions.

```bash
kubectl -n <harness-namespace> exec -it postgres-0 -- psql -U postgres -h 127.0.0.1 -Atc "select pg_current_wal_lsn();"
kubectl -n cnpg-system exec harness-pg-1 -c postgres -- psql -U postgres -Atc "select pg_last_wal_replay_lsn();"
```

The second value must be equal to or higher than the first.
{% endstep %}

{% step %}
**Promote the new cluster.** Promotion detaches the new cluster from the old database and cannot be undone.

```bash
kubectl -n cnpg-system patch cluster harness-pg --type merge -p '{"spec":{"replica":{"enabled":false}}}'
kubectl -n cnpg-system exec harness-pg-1 -c postgres -- psql -U postgres -Atc "select pg_is_in_recovery();"
```

The result must be `f`. Then upgrade Helm with the standard values, which adds the second instance.

```bash
helm upgrade harness-pg cnpg/cluster --version 0.9.0 -n cnpg-system \
  -f pg-values.yaml
```

{% hint style="warning" %}
**Do not reuse the migration values**

Never run `helm upgrade` with `pg-migrate.yaml` after promotion. It turns the replica setting back on.
{% endhint %}
{% endstep %}

{% step %}
Go to [Connect Harness to PostgreSQL](#connect-harness-to-postgresql), then scale Harness up. Keep the old PostgreSQL volume until you verify the new cluster and take a backup.
{% endstep %}
{% endstepper %}

## Connect Harness to PostgreSQL

Add these values to your Harness release, then run `helm upgrade`.

{% code title="override-prod.yaml" overflow="wrap" %}

```yaml
global:
  database:
    postgres:
      installed: false
      hosts:
        - harness-pg-rw.cnpg-system.svc.cluster.local:5432
      secretName: harness-pg-superuser
      userKey: username
      passwordKey: password
```

{% endcode %}

{% hint style="warning" %}
**Remove the bundled PostgreSQL after the cutover**

Setting `installed: false` removes the bundled PostgreSQL from the Harness release. When you migrate, apply this value only after the cutover. The old volume, `data-postgres-0`, is kept.
{% endhint %}

## Enable backups

CNPG archives WAL files continuously to object storage. It takes base backups as daily volume snapshots from the replica. Together they let you restore to any point in time.

{% hint style="warning" %}
**The Helm chart does not support volume snapshots yet**

The `cluster` chart cannot render `spec.backup.volumeSnapshot` or `bootstrap.recovery.volumeSnapshots`. Go to [cloudnative-pg/charts issue 900](https://github.com/cloudnative-pg/charts/issues/900) to follow the request.

Until the chart supports them, add the snapshot settings with the commands in this section and in [Restore from a backup](#restore-from-a-backup). Helm keeps the added fields on later upgrades.
{% endhint %}

### Check volume snapshot requirements

Base backups are volume snapshots, so the cluster must support them. Check the following before you continue.

* **CSI driver:** A CSI driver that supports snapshots. On GKE, this is the Persistent Disk CSI driver, `pd.csi.storage.gke.io`, and the PostgreSQL volumes must use a storage class that it backs, such as `standard-rwo`.
* **Snapshot components:** The `VolumeSnapshot`, `VolumeSnapshotContent`, and `VolumeSnapshotClass` custom resource definitions, and the snapshot controller.
* **Snapshot class:** A `VolumeSnapshotClass` for the CSI driver.

```bash
kubectl get crd volumesnapshots.snapshot.storage.k8s.io
kubectl get volumesnapshotclass
```

If you do not have a snapshot class, create one.

{% code title="volumesnapshotclass.yaml" overflow="wrap" %}

```yaml
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshotClass
metadata:
  name: <snapshot-class>
driver: pd.csi.storage.gke.io
deletionPolicy: Delete
parameters:
  storage-locations: <region-or-multi-region>
```

{% endcode %}

{% hint style="info" %}
**Plan for a regional failure**

Set `storage-locations` to a multi-region, such as `us`, so the snapshots stay available if the region of the cluster fails. A dual-region bucket protects only the WAL archive.

With `deletionPolicy: Delete`, deleting a `VolumeSnapshot` also deletes the Google Cloud snapshot. Deleting the namespace deletes the snapshots too.
{% endhint %}

Go to [Volume snapshots on GKE](https://cloud.google.com/kubernetes-engine/docs/how-to/persistent-volumes/volume-snapshots) to review the GKE requirements.

### Set up backups

{% stepper %}
{% step %}
**Create a bucket and grant the cluster access.** The Kubernetes service account has the same name as the cluster, `harness-pg`.

Use a dual-region bucket if possible, so the WAL archive survives the failure of a region. For example, use `nam4` for the United States or `eur4` for Europe. Go to [Bucket locations](https://cloud.google.com/storage/docs/locations) to choose a location.

This procedure uses GKE Workload Identity.

```bash
PROJECT=<project-id>
PROJECT_NUMBER=<project-number>
BUCKET=<bucket>
MEMBER="principal://iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$PROJECT.svc.id.goog/subject/ns/cnpg-system/sa/harness-pg"

gcloud storage buckets create gs://$BUCKET --project $PROJECT \
  --location <dual-region> --uniform-bucket-level-access
gcloud storage buckets add-iam-policy-binding gs://$BUCKET \
  --role roles/storage.objectAdmin --member "$MEMBER"
gcloud storage buckets add-iam-policy-binding gs://$BUCKET \
  --role roles/storage.legacyBucketReader --member "$MEMBER"
```

Go to [Object stores](https://cloudnative-pg.io/plugin-barman-cloud/docs/object_stores/) to review other authentication options.
{% endstep %}

{% step %}
**Add the snapshot settings to the cluster.** Replace `<snapshot-class>` with your `VolumeSnapshotClass`.

```bash
kubectl -n cnpg-system patch cluster harness-pg --type merge -p '{"spec":{"backup":{"volumeSnapshot":{
  "className":"<snapshot-class>","snapshotOwnerReference":"backup","online":true,
  "onlineConfiguration":{"immediateCheckpoint":true,"waitForArchive":true}}}}}'
```

Go to [Volume snapshot backups](https://cloudnative-pg.io/docs/1.30/appendixes/backup_volumesnapshot) to review these settings.
{% endstep %}

{% step %}
**Create the backup values.** The schedule runs daily at 02:00. The six fields start with seconds.

{% code title="pg-backup.yaml" overflow="wrap" %}

```yaml
backups:
  enabled: true
  method: plugin
  pluginConfiguration:
    name: barman-cloud.cloudnative-pg.io
  target: prefer-standby
  wal:
    compression: gzip
    encryption: ""
    maxParallel: 2
  data:
    encryption: ""
  provider: google
  google:
    bucket: <bucket>
    path: /harness-pg/v1
    gkeEnvironment: true
  secret:
    create: false
  scheduledBackups:
    - name: daily-snapshot
      schedule: "0 0 2 * * *"
      backupOwnerReference: none
      method: volumeSnapshot
```

{% endcode %}
{% endstep %}

{% step %}
**Apply the backup values.** The plugin adds a sidecar container, so the instances restart one after the other. Run this step outside peak hours.

```bash
helm upgrade harness-pg cnpg/cluster --version 0.9.0 -n cnpg-system \
  -f pg-values.yaml -f pg-backup.yaml
```

{% endstep %}

{% step %}
**Verify the backup.**

```bash
kubectl -n cnpg-system get backup,volumesnapshot
kubectl -n cnpg-system get cluster harness-pg \
  -o jsonpath='{.status.conditions[?(@.type=="ContinuousArchiving")].status}{"\n"}'
```

The first backup shows `completed`, the snapshot shows `READYTOUSE true`, and `ContinuousArchiving` is `True`.
{% endstep %}
{% endstepper %}

{% hint style="info" %}
**Clean up old backups**

CNPG never deletes old snapshots. Delete old `Backup` objects to remove their snapshots, and add a lifecycle rule to the bucket to expire old WAL files.
{% endhint %}

## Restore from a backup

A restore always creates a new cluster, named `harness-pg-restored` in this procedure. The running cluster is not changed. CNPG restores the snapshot, then replays WAL files up to the point in time that you choose.

{% hint style="danger" %}
**Use a new cluster name**

Never render or apply a restore with the name of the running cluster. The restore overwrites the live objects.
{% endhint %}

{% stepper %}
{% step %}
**Choose the snapshot.** The restored cluster must archive to a new, empty path.

```bash
kubectl -n cnpg-system get volumesnapshot
export SNAP=<snapshot-name>
export NEWPATH=/harness-pg/v2
```

{% endstep %}

{% step %}
**Give the new cluster access to the bucket.** Its service account is `harness-pg-restored`.

```bash
MEMBER="principal://iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$PROJECT.svc.id.goog/subject/ns/cnpg-system/sa/harness-pg-restored"
for ROLE in roles/storage.objectAdmin roles/storage.legacyBucketReader; do
  gcloud storage buckets add-iam-policy-binding gs://$BUCKET --role $ROLE --member "$MEMBER"
done
```

{% endstep %}

{% step %}
**Create the restore values.** Leave `pitrTarget.time` blank to replay all archived WAL files up to the latest point. To recover to an earlier moment, set the time in UTC, for example `2026-10-19T12:00:00Z`. The time must be after the snapshot was taken.

{% code title="pg-restore.yaml" overflow="wrap" %}

```yaml
mode: recovery
fullnameOverride: harness-pg-restored
cluster:
  instances: 1
recovery:
  method: plugin
  pluginConfiguration:
    name: barman-cloud.cloudnative-pg.io
  clusterName: harness-pg
  pitrTarget:
    time: ""  # example: 2026-10-19T12:00:00Z
  database: postgres
  owner: postgres
  provider: google
  google:
    bucket: <bucket>
    path: /harness-pg/v1
    gkeEnvironment: true
  secret:
    create: false
```

{% endcode %}
{% endstep %}

{% step %}
**Render the manifest with the snapshot settings.** Replace `<snapshot-class>`. The render also points the recovery at the existing `harness-pg-superuser` secret. Without it, CNPG generates a random password for the `postgres` owner and replaces the real one.

```bash
helm template harness-pg-restored cnpg/cluster --version 0.9.0 -n cnpg-system --skip-tests \
  -f pg-values.yaml -f pg-restore.yaml -f pg-backup.yaml \
  --set backups.google.path=$NEWPATH \
| yq '
    (select(.kind == "Cluster") | .spec.bootstrap.recovery.volumeSnapshots.storage) = {"name": strenv(SNAP), "kind": "VolumeSnapshot", "apiGroup": "snapshot.storage.k8s.io"}
  | (select(.kind == "Cluster") | .spec.bootstrap.recovery.secret.name) = "harness-pg-superuser"
  | (select(.kind == "Cluster") | .spec.backup.volumeSnapshot) = {"className": "<snapshot-class>", "snapshotOwnerReference": "backup", "online": true, "onlineConfiguration": {"immediateCheckpoint": true, "waitForArchive": true}}
  | select(.kind != "ScheduledBackup")' > restored.yaml
```

{% endstep %}

{% step %}
**Apply the manifest.** Create the object stores first, then the cluster.

```bash
yq 'select(.kind == "ObjectStore")' restored.yaml | kubectl -n cnpg-system apply -f -
sleep 5
yq 'select(.kind != "ObjectStore")' restored.yaml | kubectl -n cnpg-system apply -f -
kubectl -n cnpg-system get cluster harness-pg-restored -w
```

{% hint style="warning" %}
**Apply the object stores first**

If CNPG creates the cluster before its object stores, the cluster can stay in `BootstrapPending`. Go to [cloudnative-pg issue 11618](https://github.com/cloudnative-pg/cloudnative-pg/issues/11618) to follow the fix.
{% endhint %}
{% endstep %}

{% step %}
**Verify the recovery.**

```bash
kubectl -n cnpg-system exec harness-pg-restored-1 -c postgres -- psql -U postgres -Atc "select pg_is_in_recovery();"
kubectl -n cnpg-system exec harness-pg-restored-1 -c postgres -- psql -U postgres -Atc "select timeline_id from pg_control_checkpoint();"
```

`pg_is_in_recovery()` must return `f`, which means recovery finished and the cluster is promoted. The timeline is higher than the timeline of the source cluster. Check your data at the recovery point.
{% endstep %}

{% step %}
**Hand the cluster to Helm.** This creates the scheduled backups for the restored cluster.

```bash
kubectl -n cnpg-system annotate cluster harness-pg-restored \
  meta.helm.sh/release-name=harness-pg-restored meta.helm.sh/release-namespace=cnpg-system --overwrite
kubectl -n cnpg-system annotate configmap harness-pg-restored-monitoring-logical-replication \
  meta.helm.sh/release-name=harness-pg-restored meta.helm.sh/release-namespace=cnpg-system --overwrite

helm upgrade --install harness-pg-restored cnpg/cluster --version 0.9.0 -n cnpg-system \
  --set fullnameOverride=harness-pg-restored --set backups.google.path=$NEWPATH \
  -f pg-values.yaml -f pg-backup.yaml
```

Point Harness at `harness-pg-restored-rw.cnpg-system.svc.cluster.local` when you are ready to use the restored cluster.
{% endstep %}
{% endstepper %}

## Troubleshooting

<details>

<summary>The restored cluster stays in BootstrapPending</summary>

The cluster was created before its object stores. Apply the `ObjectStore` objects first, wait a few seconds, then apply the rest of the manifest.

</details>

<details>

<summary>ContinuousArchiving is False with a 403 error on Google Cloud Storage</summary>

The service account of the cluster needs both `roles/storage.objectAdmin` and `roles/storage.legacyBucketReader` on the bucket. The first WAL archive checks the bucket, which requires `storage.buckets.get`. The restored cluster has its own service account, so grant the roles to `harness-pg-restored` as well.

</details>

<details>

<summary>The restore fails with "Expected empty archive"</summary>

A new cluster must archive to an empty path. Set `NEWPATH` to a path that does not exist in the bucket, or delete the contents of the old path of a previous test restore.

</details>

## Next steps

{% content-ref url="/pages/b13FVJsCGZ3n3Pm0gCUe" %}
[Configure external databases](https://developer.harness.io/self-managed-enterprise-edition/use-self-managed-enterprise-edition/advanced-configuration/external-db/configure-external-databases.md)
{% endcontent-ref %}

{% @harness-feedback/feedback %}
