pg
by cagriekin
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 (therepmgrdandservice-updatersidecars 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>-readonlyservice 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
| Parameter | Description | Default |
|---|---|---|
imagePullSecrets | Pull secrets applied to every pod template (StatefulSet, pgpool and exporter Deployments, backup and pgBackRest CronJobs) | [] |
busyboxImage.repository | Image for the helper init containers (permission fixups, config copy/templating) across the StatefulSet, pgpool, and exporter pods; override for air-gapped/private registries | busybox |
busyboxImage.tag | Helper init image tag | 1.37 |
busyboxImage.pullPolicy | Helper init image pull policy | IfNotPresent |
busyboxImage.digest | Optional 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, andpgbackrest.cronjob.image— accepts an optionaldigest(e.g.sha256:…). When set, the image is rendered asrepository:tag@digestso a mutable-tag repush cannot silently change what runs. Empty (default) pulls by tag.
PostgreSQL Parameters
| Parameter | Description | Default |
|---|---|---|
postgresql.image.repository | PostgreSQL image repository | postgres |
postgresql.image.tag | PostgreSQL image tag | 18.1-trixie |
postgresql.image.pullPolicy | Image pull policy | IfNotPresent |
postgresql.majorVersion | PostgreSQL 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.replicaCount | Number of PostgreSQL replicas (total instances = replicaCount + 1); values > 0 require ha.enabled=true | 1 |
postgresql.database | Database name | postgres |
postgresql.username | Database username (a superuser; the chart's own tooling logs in as it) | postgres |
postgresql.app.username | Non-superuser application role, owns postgresql.database (except postgres) -- see Application role and connection reserves | app_user |
postgresql.resources.requests.cpu | CPU request | 100m |
postgresql.resources.requests.memory | Memory request | 256Mi |
postgresql.resources.limits.cpu | CPU limit | 1000m |
postgresql.resources.limits.memory | Memory limit | 1Gi |
postgresql.standbyResources | Size 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.standbyResourcesAcknowledgeReads | Allow 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 sizing | false |
postgresql.persistence.enabled | Enable persistence | true |
postgresql.persistence.size | Storage size | 10Gi |
postgresql.persistence.emptyDir.sizeLimit | sizeLimit for the non-persistent (persistence.enabled=false) PGDATA emptyDir; empty = fall back to persistence.size (never unbounded) | "" |
postgresql.persistence.storageClass | Storage class | "" |
postgresql.updateStrategy.type | StatefulSet update strategy | RollingUpdate |
postgresql.updateStrategy.rollingUpdate.partition | Partition for rolling update | 0 |
postgresql.podAnnotations | Annotations for PostgreSQL pods | {} |
postgresql.priorityClassName | priorityClassName for PostgreSQL pods | "" |
postgresql.affinity | Affinity rules for PostgreSQL pods | {} |
postgresql.annotations | Additional annotations | {} |
postgresql.podSecurityContext | Pod-level securityContext for StatefulSet | {fsGroup: 103, runAsNonRoot: true, seccompProfile.type: RuntimeDefault} |
postgresql.containerSecurityContext | Container-level securityContext for all PostgreSQL containers | {runAsUser: 101, runAsGroup: 103, allowPrivilegeEscalation: false, capabilities.drop: [ALL]} |
Liveness and Readiness Probes
| Parameter | Description | Default |
|---|---|---|
postgresql.livenessProbe.enabled | Enable liveness probe | true |
postgresql.livenessProbe.initialDelaySeconds | Initial delay | 30 |
postgresql.livenessProbe.periodSeconds | Check interval | 10 |
postgresql.livenessProbe.timeoutSeconds | Timeout | 5 |
postgresql.livenessProbe.failureThreshold | Failure threshold | 10 |
postgresql.readinessProbe.enabled | Enable readiness probe | true |
postgresql.readinessProbe.initialDelaySeconds | Initial delay | 5 |
postgresql.readinessProbe.periodSeconds | Check interval | 10 |
postgresql.readinessProbe.timeoutSeconds | Timeout | 5 |
postgresql.readinessProbe.failureThreshold | Failure threshold | 6 |
postgresql.startupProbe.enabled | Enable 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.periodSeconds | Check interval | 10 |
postgresql.startupProbe.timeoutSeconds | Timeout | 5 |
postgresql.startupProbe.failureThreshold | Failure 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_connectionsexhausted, including the superuser slots. The agent keeps one persistent loopback session, so clients exhaustingmax_connectionsalone 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
RollingUpdatenever advances onto the clone source; postgresql.tls.enabledis set and the server reportsssl = 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
| Parameter | Description | Default |
|---|---|---|
postgresql.podDisruptionBudget.enabled | Enable PDB for PostgreSQL | true |
postgresql.podDisruptionBudget.maxUnavailable | Max pods unavailable during a voluntary disruption | 1 |
postgresql.podDisruptionBudget.unhealthyPodEvictionPolicy | Allow evicting not-yet-Ready pods so a stuck pod cannot wedge a drain (k8s >=1.27) | AlwaysAllow |
pgpool.podDisruptionBudget.enabled | Enable PDB for PGPool-II | true |
pgpool.podDisruptionBudget.minAvailable | Minimum available pods | 1 |
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.
| Parameter | Description | Default |
|---|---|---|
postgresql.configuration | Map of postgresql.conf parameters | {} |
postgresql.pgHba | List 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.extraVolumes | Extra pod-level volumes (see Mounting an extra file on every replica) | [] |
postgresql.extraVolumeMounts | Extra mounts for the postgresql container; each must reference a postgresql.extraVolumes entry | [] |
postgresql.extraEnv | Extra env vars for the postgresql container (supports value and valueFrom); may not reuse a chart-set name | [] |
postgresql.extensions.enabled | Enable extensions support | false |
postgresql.extensions.packages | Debian/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.aptSources | Non-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.repository | Prebuilt 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.tag | Tag 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.
- Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
- Place the chartpg is pinned at v2.8.0 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
- 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