Configuration

How to configure a CloudNativePG Cluster on Alauda Container Platform: PostgreSQL parameters, users and databases, replication, storage, and images. For first deployment see the Quick Start; for the architecture see Architecture.

PostgreSQL parameters

spec:
  postgresql:
    parameters:
      shared_buffers: 512MB
      max_connections: "200"
      work_mem: 8MB
    pg_hba:
      - host all all 10.0.0.0/8 scram-sha-256
  • A set of parameters is operator-controlled and rejected if set (archive_mode, archive_command, restore_command, port, hot_standby, ssl*, synchronous_standby_names, shared_preload_libraries, recovery targets, listen/log/file-path settings). Use the dedicated fields instead: spec.postgresql.shared_preload_libraries, spec.postgresql.synchronous (below).
  • Commonly tuned parameters (max_connections, shared_buffers, work_mem, effective_cache_size, autovacuum and checkpoint settings, …) are all allowed.
  • The operator injects sensible defaults, including wal_level=logical, archive_timeout=5min, wal_keep_size=512MB, and TLS ≥ 1.3.
  • ALTER SYSTEM is disabled by default (spec.postgresql.enableAlterSystem) — configuration is declarative; changes roll through the cluster governed by spec.primaryUpdateStrategy (unsupervised default) and spec.primaryUpdateMethod (restart or switchover).
  • pg_hba entries are inserted between operator-managed fixed rules (local peer access, certificate-authenticated replication) and a trailing default of host all all all scram-sha-256.

Users and databases

CloudNativePG never stores passwords inline in the Cluster resource. Every password the operator applies comes from a Kubernetes Secret of type kubernetes.io/basic-auth in the same namespace as the cluster. You either let the operator generate those Secrets, or you create them yourself and reference them by name.

PostgreSQL roleConfigured byDefaultSecret it reads
Application owner (app)spec.bootstrap.initdbcreated, random password<cluster>-app, or spec.bootstrap.initdb.secret
Superuser (postgres)spec.enableSuperuserAccess, spec.superuserSecretno password (network login disabled)<cluster>-superuser, or spec.superuserSecret
Additional rolesDatabaseRole resources or spec.managed.rolesnot createdpasswordSecret per role

Credential Secrets

A credential Secret you create yourself must:

  • have type: kubernetes.io/basic-auth with the keys username and password;
  • carry a username that exactly matches the PostgreSQL role it is used for (app / the initdb.owner, postgres, or the managed role name). A mismatch is rejected by the instance manager and the password is not applied;
  • carry the label cnpg.io/reload: "true". The operator only watches Secrets with this label, so with the label a password change is applied to PostgreSQL immediately; without it the change is picked up only at a later, unrelated reconciliation. Secrets generated by the operator already carry this label.

With kubectl:

kubectl create secret generic pg-demo-app-creds -n pg-demo \
  --type=kubernetes.io/basic-auth \
  --from-literal=username=app \
  --from-literal=password='S3cure-Passw0rd'
kubectl label secret pg-demo-app-creds -n pg-demo cnpg.io/reload=true

Or declaratively:

apiVersion: v1
kind: Secret
metadata:
  name: pg-demo-app-creds
  namespace: pg-demo
  labels:
    cnpg.io/reload: "true"
type: kubernetes.io/basic-auth
stringData:
  username: app
  password: S3cure-Passw0rd

A Secret you create contains only username and password. Secrets the operator generates (<cluster>-app, <cluster>-superuser) contain ready-to-use connection details as well:

KeyContent
username, userRole name
passwordGenerated password
dbnameDatabase name (* in the superuser Secret)
host, portRead-write Service name, 5432
uri, jdbc-uriConnection strings using the namespaced Service host
fqdn-uri, fqdn-jdbc-uriSame, using the fully qualified Service host
pgpassA line in .pgpass format

Application database and owner password

spec.bootstrap.initdb creates the application database and its owner. By default the database is app, the owner is app, and the operator generates the <cluster>-app Secret with a random password.

To choose the password when the cluster is created, create the credential Secret first (see above — username must equal spec.bootstrap.initdb.owner), then reference it:

spec:
  bootstrap:
    initdb:
      database: app
      owner: app
      secret:
        name: pg-demo-app-creds   # no <cluster>-app Secret is generated

spec.bootstrap.recovery.secret and spec.bootstrap.pg_basebackup.secret accept an application-owner Secret in the same way when a cluster is bootstrapped from a backup or cloned from another cluster.

Changing the password later: update the password key of the Secret in use (<cluster>-app or the one referenced by initdb.secret). With the cnpg.io/reload: "true" label, the instance manager runs ALTER ROLE on the primary right away; clients must reconnect with the new password.

kubectl patch secret pg-demo-app-creds -n pg-demo --type=merge \
  -p '{"stringData":{"password":"N3w-Passw0rd"}}'

Superuser (postgres) password

Superuser access over the network is disabled by default (spec.enableSuperuserAccess: false): the operator sets the postgres role's password to NULL and manages the instance through local peer and TLS client-certificate authentication only.

  • Generated password: set spec.enableSuperuserAccess: true. The operator creates the <cluster>-superuser Secret.

  • Your own password: create a credential Secret with username: postgres (and the cnpg.io/reload: "true" label), then set both fields:

    spec:
      enableSuperuserAccess: true
      superuserSecret:
        name: pg-demo-superuser-creds
WARNING

spec.superuserSecret has no effect unless spec.enableSuperuserAccess is true. With access disabled the operator ignores the Secret's content and keeps the postgres password NULL; setting enableSuperuserAccess back to false later also deletes the operator-generated <cluster>-superuser Secret (a Secret you created yourself is left in place).

Additional roles

Additional roles are declarative. Two forms are available and can be used side by side for different roles:

  • DatabaseRole resources (recommended) — one resource per role, independent of the Cluster manifest. Suited to GitOps and to letting application teams manage their own roles.
  • spec.managed.roles — roles listed inline in the Cluster.

DatabaseRole example — the resource, the referenced Cluster and the password Secret must all be in the same namespace:

apiVersion: postgresql.cnpg.io/v1
kind: DatabaseRole
metadata:
  name: pg-demo-alice
  namespace: pg-demo
spec:
  cluster:
    name: pg-demo
  name: alice                      # PostgreSQL role name (immutable)
  login: true                      # roles default to login: false
  createdb: true
  inRoles:
    - pg_monitor
  passwordSecret:
    name: alice-creds              # basic-auth Secret, username: alice
  databaseRoleReclaimPolicy: retain   # retain (default) | delete

Equivalent inline form:

spec:
  managed:
    roles:
      - name: alice
        ensure: present          # present (default) | absent
        login: true
        createdb: true
        inRoles:
          - pg_monitor
        passwordSecret:
          name: alice-creds

Points to keep in mind:

  • Roles default to login: false. Set login: true for any role that clients connect with.
  • Without passwordSecret the role is created with a NULL password. disablePassword: true explicitly sets it to NULL; it cannot be combined with passwordSecret.
  • Removing a role: inline roles use ensure: absent. A DatabaseRole does not accept ensure; delete the resource instead, and databaseRoleReclaimPolicy decides what happens in PostgreSQL — retain (default) keeps the role, delete runs DROP ROLE (which fails, and the resource stays Terminating, while the role still owns objects).
  • If the same role name is declared in both spec.managed.roles and a DatabaseRole, spec.managed.roles takes precedence: the DatabaseRole is not applied and reports applied: false with database role is already managed by the CNPG cluster.
  • A DatabaseRole pointed at a role that already exists adopts it and resets every attribute you omit (for example, memberships not in inRoles are revoked). The names postgres, streaming_replica, and names starting with pg_ or cnpg_ are reserved.
  • Check progress with kubectl get databaserole -n pg-demo (Applied column).

Additional databases

Additional databases are their own Database resources:

apiVersion: postgresql.cnpg.io/v1
kind: Database
metadata:
  name: pg-demo-reporting
  namespace: pg-demo
spec:
  cluster:
    name: pg-demo
  name: reporting                 # PostgreSQL database name
  owner: alice                    # an existing role, e.g. from a DatabaseRole
  extensions:
    - name: vector                # pgvector
      ensure: present
  databaseReclaimPolicy: retain   # retain (default) | delete

With databaseReclaimPolicy: delete, deleting the Database resource also drops the database in PostgreSQL; with retain the database is kept.

Creating a cluster from the Console

TIP

In the ACP Console (Data Services → CloudNativePG → Create), the Form view creates the cluster with the defaults described above: an app database and owner whose password is generated into the <cluster>-app Secret, and no superuser password.

To set your own passwords at creation time (bootstrap.initdb.secret, superuserSecret, or roles under managed.roles), first create the kubernetes.io/basic-auth Secrets in the target namespace, then switch the Create page to the YAML view and add the fields shown above — or apply the manifest with kubectl. Generated passwords can be read from the <cluster>-app / <cluster>-superuser Secrets at any time.

Extensions and pgaudit

The standard PostgreSQL operands bundle pgvector, pgaudit, PostGIS, zhparser, TimescaleDB (Apache-2 OSS, PG 15+), and pg_failover_slots — all available without the Kubernetes ImageVolume feature gate.

Most extensions are enabled per-database with a Database resource (spec.extensions, see above) or a plain CREATE EXTENSION. Two are load-time extensions and must be declared via spec.postgresql.shared_preload_libraries (the bare shared_preload_libraries GUC is operator-controlled and rejected):

spec:
  postgresql:
    shared_preload_libraries:
      - pgaudit
      - pg_failover_slots
      - timescaledb        # PG 15+ only
    parameters:
      pgaudit.log: "ddl, write"   # configure pgaudit declaratively
  • pgaudit must be configured declaratively. It is an operator-managed extension: a manual CREATE EXTENSION pgaudit is dropped on the next restart. Add pgaudit to shared_preload_libraries and set pgaudit.* parameters as above — the operator creates and maintains the extension for you.
  • pg_failover_slots is preload-only by design (no CREATE EXTENSION step): once in shared_preload_libraries it synchronizes logical replication slots to standbys automatically.
  • timescaledb requires shared_preload_libraries and is available on PG 15–18 only (no OSS package for PG 14 on Debian trixie). Only the Apache-2 edition is shipped — TSL features (compression, continuous aggregates) are not included.

Replication and high availability

spec:
  instances: 3
  postgresql:
    synchronous:                 # optional synchronous replication
      method: any
      number: 1
      dataDurability: required   # 'preferred' favors availability
  affinity:
    podAntiAffinityType: required   # default 'preferred'
    topologyKey: kubernetes.io/hostname

Failover is automatic (the operator promotes the most advanced replica). Manual switchover is available through the cnpg kubectl plugin (kubectl cnpg promote <cluster> <instance>).

Services and external access

Every cluster gets three ClusterIP services:

ServiceRoutes to
<cluster>-rwthe primary (read-write)
<cluster>-roreplicas only (read-only)
<cluster>-rany instance

These services are always ClusterIP. Do not change their type with kubectl edit/patch: the change is not declared anywhere and is lost whenever the service is recreated (for example after a restore). To reach the database with a different service type (NodePort, LoadBalancer), declare an additional service in the Cluster:

spec:
  managed:
    services:
      disabledDefaultServices: ["ro", "r"]   # optional; rw cannot be disabled
      additional:
        - selectorType: rw                   # rw | ro | r
          updateStrategy: patch              # default; or replace
          serviceTemplate:
            metadata:
              name: pg-demo-rw-nodeport      # must not be <cluster>-rw/-ro/-r
              annotations: {}                # optional, e.g. load-balancer settings
            spec:
              type: NodePort                 # or LoadBalancer
              ports:                         # optional; only to pin the nodePort
                - name: postgres
                  port: 5432
                  targetPort: 5432
                  nodePort: 30432
  • The operator owns the service selector (from selectorType), so do not set spec.selector. The service follows the primary across failover and switchover.
  • Editing serviceTemplate changes the live service, including its type. Removing an entry from additional deletes that service.
  • updateStrategy: patch (default) applies only the fields you changed in the template since the last reconcile. It does not revert out-of-band edits to the live service. Example: change type to ClusterIP and back to NodePort while keeping a pinned nodePort. The service comes back with a random port, and the operator reports no error. Use updateStrategy: replace to force the live service to match the template exactly. replace deletes and recreates the service on every change, so connections through that service are briefly interrupted and the ClusterIP/nodePort may change unless pinned.
  • A LoadBalancer service needs a load-balancer implementation in the cluster; without one, EXTERNAL-IP stays <pending>.
  • The admission webhook rejects disabling rw, reusing a reserved <cluster>-rw/-ro/-r name, and duplicate service names.
  • Exposing PostgreSQL outside the cluster widens its attack surface. Restrict clients with pg_hba and, for LoadBalancer, spec.loadBalancerSourceRanges.

Storage

spec:
  storage:
    size: 10Gi                  # grow in place by raising it (no shrink)
    storageClass: sc-topolvm    # use a TopoLVM class for production
  walStorage:                   # optional dedicated WAL volume
    size: 5Gi
    storageClass: sc-topolvm

Tablespaces are supported via spec.tablespaces (each gets its own PVC).

Images and upgrades

Operand images default to the version shipped with the operator bundle. To pin explicitly, set spec.imageName to a PostgreSQL operand image from your platform registry — always use an immutable tag. Minor version updates are rolling restarts; major upgrades are declarative (change the image major; the cluster performs an offline upgrade). See Upgrade.

IPv6 note

On single-stack IPv6 clusters, operator versions without the upstream url.Build bracket fix (upstream PR #10682) cannot reach instance managers over bare IPv6 pod IPs. Dual-stack clusters are unaffected. Consult the release notes of your operator version.

Troubleshooting quick reference

SymptomFirst checks
Cluster stuck in Setting up primaryinitdb job pod events: image pull, PVC pending, storage class
Unable to create required cluster objectsoperator RBAC in the target namespace
No metrics in PrometheusPodMonitor label prometheus: kube-prometheus present? See the Grafana dashboards guide (How To section)
Backup stuckbarman-cloud plugin logs in cnpg-system; ObjectStore credentials/endpoint
LoadBalancer service EXTERNAL-IP stays <pending>the cluster has no load-balancer provider; use NodePort, see Services and external access
WAL volume fillingWAL archiving broken — check WAL segments awaiting archive on the backup dashboard

Trademark Notice

CloudNativePG™ is a trademark of The Linux Foundation.

PostgreSQL® is a registered trademark of the PostgreSQL Community Association of Canada.

Alauda is an independent vendor. This product is not affiliated with, endorsed by, or sponsored by The Linux Foundation, PostgreSQL Community Association of Canada. All trademarks are the property of their respective owners and are used here for identification purposes only.