pg

by cagriekin

Helm chartv2.8.0App 18Verified publisher

Highly-available PostgreSQL with streaming replication, automatic agent failover (Kubernetes Lease or etcd-quorum DCS), optional PgPool-II, pgBackRest S3 backups, TLS, and Prometheus metrics

About this chart

Highly-available PostgreSQL with PGPool-II

PostgreSQL Helm chart with native streaming replication and a lease-based Go failover agent, optional PGPool-II for connection pooling and read/write splitting. (repmgr drove replication through 1.x; 2.0.0 replaced it with the agent and removed it from the image — see Upgrading to 2.0.0.)

Features

  • PostgreSQL 18 with configurable major (18 or 17)
  • Lease-based HA agent (pg-ha-agent, PID 1 in the postgresql container) for automatic failover, replication management, and primary Service selector updates — no HA sidecars (the repmgrd and service-updater sidecars were removed in 2.0.0; the pgBackRest and metrics-exporter sidecars are unaffected)
  • Stale-primary protection: a crashed primary that restarts after a standby was promoted rejoins as a standby (via pg_rewind) instead of resuming read-write on a divergent timeline
  • Read-only <fullname>-readonly service targeting standby pods for read scaling (HA mode)
  • Optional PGPool-II for connection pooling and read/write splitting
  • Support for existing secrets or auto-generated passwords
  • StatefulSet-based deployment with persistent storage
  • PostgreSQL configuration injection via ConfigMap (postgresql.conf overrides, pg_hba.conf entries)
  • PostStart lifecycle hooks with primary-aware execution in HA setups
  • Pod disruption budgets for safe node drains
  • Configurable update strategy, resource limits, probes, and affinity
  • Prometheus exporters for PostgreSQL and PGPool-II metrics with ServiceMonitor support
  • Automated S3 backups via CronJob with retention management

Installation

helm repo add cagriekin https://cagriekin.github.io/charts
helm install my-postgres cagriekin/pg

With Read Replicas

helm install my-postgres cagriekin/pg --set postgresql.replicaCount=3

With PGPool-II Enabled

helm install my-postgres cagriekin/pg \
  --set postgresql.replicaCount=3 \
  --set pgpool.enabled=true

With Existing Secret

kubectl create secret generic pg-secret \
  --from-literal=username=myuser \
  --from-literal=password=mypassword \
  --from-literal=database=mydb \
  --from-literal=repmgr-password=myrepmgrpassword

helm install my-postgres cagriekin/pg \
  --set postgresql.existingSecret.enabled=true \
  --set postgresql.existingSecret.name=pg-secret

Or with custom key names:

kubectl create secret generic pg-secret \
  --from-literal=user=myuser \
  --from-literal=pass=mypassword \
  --from-literal=db=mydb \
  --from-literal=repmgr-pass=myrepmgrpassword

helm install my-postgres cagriekin/pg \
  --set postgresql.existingSecret.enabled=true \
  --set postgresql.existingSecret.name=pg-secret \
  --set postgresql.existingSecret.usernameKey=user \
  --set postgresql.existingSecret.passwordKey=pass \
  --set postgresql.existingSecret.databaseKey=db \
  --set postgresql.existingSecret.repmgrPasswordKey=repmgr-pass

Without an existing secret the chart generates random passwords on install and reuses them on subsequent upgrades by looking up the live secret. Helm's lookup returns nothing under helm template/--dry-run, so rendering pipelines that never talk to the cluster (e.g. ArgoCD) must use postgresql.existingSecret to keep credentials stable.

Configuration

Common Parameters

ParameterDescriptionDefault
imagePullSecretsPull secrets applied to every pod template (StatefulSet, pgpool and exporter Deployments, backup and pgBackRest CronJobs)[]
busyboxImage.repositoryImage for the helper init containers (permission fixups, config copy/templating) across the StatefulSet, pgpool, and exporter pods; override for air-gapped/private registriesbusybox
busyboxImage.tagHelper init image tag1.37
busyboxImage.pullPolicyHelper init image pull policyIfNotPresent
busyboxImage.digestOptional digest pin (sha256:...), appended as repository:tag@digest""

Pinning images by digest (#26). Every image block — postgresql.image, ha.image, pgpool.image, pgpool.metrics.image, prometheusExporter.image, busyboxImage, backup.rclone.image, and pgbackrest.cronjob.image — accepts an optional digest (e.g. sha256:…). When set, the image is rendered as repository:tag@digest so a mutable-tag repush cannot silently change what runs. Empty (default) pulls by tag.

PostgreSQL Parameters

ParameterDescriptionDefault
postgresql.image.repositoryPostgreSQL image repositorypostgres
postgresql.image.tagPostgreSQL image tag18.1-trixie
postgresql.image.pullPolicyImage pull policyIfNotPresent
postgresql.majorVersionPostgreSQL major version in image.tag; builds the extension paths (/usr/lib/postgresql/<major>/lib, /usr/share/postgresql/<major>/extension) when extensions.enabled=true. With ha.enabled the server runs from the HA image and follows ha.image.majorVersion regardless of postgresql.image; the chart fails to render if the two majors differ. Set both to "17" (with a -pg17 HA image tag) to run PostgreSQL 17 — see Choosing the PostgreSQL major."18"
postgresql.replicaCountNumber of PostgreSQL replicas (total instances = replicaCount + 1); values > 0 require ha.enabled=true1
postgresql.databaseDatabase namepostgres
postgresql.usernameDatabase username (a superuser; the chart's own tooling logs in as it)postgres
postgresql.app.usernameNon-superuser application role, owns postgresql.database (except postgres) -- see Application role and connection reservesapp_user
postgresql.resources.requests.cpuCPU request100m
postgresql.resources.requests.memoryMemory request256Mi
postgresql.resources.limits.cpuCPU limit1000m
postgresql.resources.limits.memoryMemory limit1Gi
postgresql.standbyResourcesSize of every pod that is not the primary; the agent resizes its own pod in place to postgresql.resources on promotion and back on demotion. Empty = one size. See Standby sizing{}
postgresql.standbyResourcesAcknowledgeReadsAllow standbyResources with pgpool.enabled, whose read load balancing sends reads to the standbys. Set only once every standby is tagged pg-ha/noloadbalance, or when reads at the standby size are intended. See Standby sizingfalse
postgresql.persistence.enabledEnable persistencetrue
postgresql.persistence.sizeStorage size10Gi
postgresql.persistence.emptyDir.sizeLimitsizeLimit for the non-persistent (persistence.enabled=false) PGDATA emptyDir; empty = fall back to persistence.size (never unbounded)""
postgresql.persistence.storageClassStorage class""
postgresql.updateStrategy.typeStatefulSet update strategyRollingUpdate
postgresql.updateStrategy.rollingUpdate.partitionPartition for rolling update0
postgresql.podAnnotationsAnnotations for PostgreSQL pods{}
postgresql.priorityClassNamepriorityClassName for PostgreSQL pods""
postgresql.affinityAffinity rules for PostgreSQL pods{}
postgresql.annotationsAdditional annotations{}
postgresql.podSecurityContextPod-level securityContext for StatefulSet{fsGroup: 103, runAsNonRoot: true, seccompProfile.type: RuntimeDefault}
postgresql.containerSecurityContextContainer-level securityContext for all PostgreSQL containers{runAsUser: 101, runAsGroup: 103, allowPrivilegeEscalation: false, capabilities.drop: [ALL]}

Liveness and Readiness Probes

ParameterDescriptionDefault
postgresql.livenessProbe.enabledEnable liveness probetrue
postgresql.livenessProbe.initialDelaySecondsInitial delay30
postgresql.livenessProbe.periodSecondsCheck interval10
postgresql.livenessProbe.timeoutSecondsTimeout5
postgresql.livenessProbe.failureThresholdFailure threshold10
postgresql.readinessProbe.enabledEnable readiness probetrue
postgresql.readinessProbe.initialDelaySecondsInitial delay5
postgresql.readinessProbe.periodSecondsCheck interval10
postgresql.readinessProbe.timeoutSecondsTimeout5
postgresql.readinessProbe.failureThresholdFailure threshold6
postgresql.startupProbe.enabledEnable startup probe (suspends liveness/readiness until PostgreSQL first accepts connections over loopback TCP — the bootstrap's socket-only transient postmaster no longer counts, #350 — so first-boot recovery and WAL replay cannot be killed by the liveness probe)true
postgresql.startupProbe.periodSecondsCheck interval10
postgresql.startupProbe.timeoutSecondsTimeout5
postgresql.startupProbe.failureThresholdFailure threshold (periodSeconds x this = total startup budget, 1800s; it also bounds a standby's first clone, #288, and in standalone mode how long the postStart hook waits for the real server before failing, floor 300s, #370)180

The startup probe, and the readiness probe in standalone mode, ask pg_isready over 127.0.0.1 (#350): loopback is the one address the bootstrap's transient postmaster and the stock image's init-time server never open, so Ready and the end of the startup grace mean the real postmaster. listen_addresses must therefore keep IPv4 loopback; a postgresql.configuration.listen_addresses without *, 0.0.0.0, localhost or 127.0.0.1 fails the render (the HA agent connects to its own postmaster there too). An IPv6-only ::/::1 does not count: PostgreSQL binds it IPV6_V6ONLY, so it never answers 127.0.0.1.

In agent mode the readiness probe is httpGet /readyz on the agent's metrics port (#395). The agent answers it from what its reconcile loop already reads over its own 127.0.0.1 connection, so no psql or pg_isready process runs per probe (the exec probe cost about 22m CPU per idle pod). It answers 503, with the reason in the body, while:

  • postgres does not answer on 127.0.0.1 (starting, recovering, cloning, mid-bootstrap or stopped);
  • postgres refuses the agent's own redial with max_connections exhausted, including the superuser slots. The agent keeps one persistent loopback session, so clients exhausting max_connections alone leave the pod Ready (the exec probe dialled fresh and went NotReady);
  • the pod is a standby whose walreceiver is not streaming (cloning or catching up, #186), so a RollingUpdate never advances onto the clone source;
  • postgresql.tls.enabled is set and the server reports ssl = off (#335);
  • the agent's last verdict is older than three ha.agent.reconcileIntervals, so a wedged agent cannot keep reporting its last good answer.

This needs the pg-ha image at 2.6.0 or later; an older chart-scheme ha.image.tag fails the render, because an older agent's /readyz answers 200 whenever its process is up.

Pod Disruption Budgets

ParameterDescriptionDefault
postgresql.podDisruptionBudget.enabledEnable PDB for PostgreSQLtrue
postgresql.podDisruptionBudget.maxUnavailableMax pods unavailable during a voluntary disruption1
postgresql.podDisruptionBudget.unhealthyPodEvictionPolicyAllow evicting not-yet-Ready pods so a stuck pod cannot wedge a drain (k8s >=1.27)AlwaysAllow
pgpool.podDisruptionBudget.enabledEnable PDB for PGPool-IItrue
pgpool.podDisruptionBudget.minAvailableMinimum available pods1

PostgreSQL Configuration

Runtime configuration can be injected without rebuilding images. Settings are written to a ConfigMap, mounted into the pod, and loaded via include_dir.

ParameterDescriptionDefault
postgresql.configurationMap of postgresql.conf parameters{}
postgresql.pgHbaList of pg_hba.conf entries, written by the agent (HA) or by the postStart hook once the real server answers (standalone; the hook reports what it did in the container log, #370)[]
postgresql.extraVolumesExtra pod-level volumes (see Mounting an extra file on every replica)[]
postgresql.extraVolumeMountsExtra mounts for the postgresql container; each must reference a postgresql.extraVolumes entry[]
postgresql.extraEnvExtra env vars for the postgresql container (supports value and valueFrom); may not reuse a chart-set name[]
postgresql.extensions.enabledEnable extensions supportfalse
postgresql.extensions.packagesDebian/PGDG packages to apt-get install before the copy step, so extensions absent from the donor image (pg_cron, postgis, …) install without a custom image; {major} substitutes postgresql.majorVersion (see Installing extensions without a custom image)[]
postgresql.extensions.aptSourcesNon-PGDG apt sources (e.g. Pigsty) to add before installing packages, for extensions PGDG doesn't package (see Installing packages from a non-PGDG apt source)[]
postgresql.extensions.image.repositoryPrebuilt extension image — packages resolved once at build time, so pods do a plain cp with no apt and no egress on the pod-start path (see Taking the install off the pod-start path)""
postgresql.extensions.image.tagTag for the above; `{major

Deploy pg with OpenTenant

Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has pg on a Hetzner server. Change the host, add apps from the marketplace, then copy the generated files. Providers and prices are samples, and nothing here is sent anywhere.

  1. Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
  2. Place the chartpg is pinned at v2.8.0 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
  3. ApplySave opentenant.yaml and main.tf from the console, then run the commands below.
# opentenant.yaml, main.tf and dns.tf come from the builder below
opentenant validate opentenant.yaml
terraform init && terraform apply