postgresql

by somaz94

Helm chartv0.1.5App 18-alpineApache-2.0Verified publisher

Standalone single-node PostgreSQL — Deployment + ConfigMap (postgresql.conf + pg_hba.conf) + Secret + PVC + Service, optional backup CronJob (pg_dump), NetworkPolicy, ServiceAccount, log emptyDir for logging_collector. Recreate strategy. Suits dev/staging single-replica installs and legacy raw-YAML migrations (existingClaim / existingSecret / fullnameOverride for in-place adoption).

About this chart

postgresql

Standalone single-node PostgreSQL chart — Deployment + ConfigMap (postgresql.conf + pg_hba.conf) + Secret + PVC + Service, optional backup CronJob, NetworkPolicy, ServiceAccount, log emptyDir for logging_collector workloads, and chart-managed image pull Secret. Designed for dev / staging / single-replica installs and in-place migration off legacy raw-YAML deployments (existingClaim, existingSecret, fullnameOverride, custom secret-key names).

For HA prefer an external managed DB (RDS / CloudSQL / Patroni) — out of scope.

What it deploys

ResourceAlways renderedNotes
Deploymentyessingle replica, Recreate strategy
ServiceyesClusterIP default, NodePort opt-in
ConfigMapyespostgresql.conf + pg_hba.conf mounted at /etc/postgresql
Secretwhen auth.existingSecret is emptyrenders POSTGRES_USER + POSTGRES_PASSWORD (key names configurable)
PersistentVolumeClaimwhen persistence.enabled is true and persistence.existingClaim is emptydata dir = pgData (default /var/lib/postgresql/data/pgdata)
Secret (dockerconfigjson)when imagePullSecret.create is trueadditive to imagePullSecrets[]
ServiceAccountwhen serviceAccount.create is truescope-pinned IRSA / pull Secrets
NetworkPolicywhen networkPolicy.enabled is truenative networking.k8s.io/v1 shape
CronJob + backup PersistentVolumeClaimwhen backup.enabled is truedaily pg_dump (or pg_dumpall when auth.database is empty) + write-time verification + retention

Prerequisites

  • Kubernetes >= 1.25
  • A StorageClass for the data PVC (or supply persistence.existingClaim)
  • The PVC must be empty on first install (initdb writes to pgData). Migration paths reuse a fully populated PVC — see "Adoption" below.

Install

OCI registry (Helm 3.8+)

helm install myapp-postgres oci://ghcr.io/somaz94/charts/postgresql --version 0.1.0 \
  --namespace myapp-db-redis --create-namespace \
  --set auth.user=myapp \
  --set auth.password='<password>' \
  --set auth.database=myapp

Classic Helm repo

helm repo add somaz94 https://charts.somaz.blog
helm install myapp-postgres somaz94/postgresql --version 0.1.0 \
  --namespace myapp-db-redis --create-namespace \
  -f my-values.yaml

Quick examples

1. Default — chart-managed Secret + PVC

auth:
  user: myapp
  password: changeme
  database: myapp
persistence:
  size: 20Gi
service:
  type: ClusterIP

2. NodePort + tuned config

auth:
  user: myapp
  password: changeme
  database: myapp
service:
  type: NodePort
  nodePort: 30632
customConfig:
  postgresqlConf: |
    listen_addresses = '*'
    max_connections = 5000
    shared_buffers = 1GB
    effective_cache_size = 3GB
    log_min_duration_statement = 2000
    statement_timeout = 120000
  pgHbaConf: |
    local   all             all                                     trust
    host    all             all             0.0.0.0/0               md5
    host    all             all             ::0/0                   md5

3. Adopt a pre-existing raw-YAML deployment in place (no data movement)

This pattern lets you migrate a legacy kubectl apply -f db.yaml install to Helm management without restoring from backup. Existing PVC, Secret and ConfigMap are reused; the chart only takes ownership of the Deployment and Service.

fullnameOverride: myapp-postgresql-db
configMap:
  nameOverride: myapp-postgresql-db-config

# Reuse the legacy Secret. Original keys were `DB_USERNAME` / `POSTGRES_PASSWORD`
# (the legacy raw-YAML used POSTGRES_DB as a literal env value, not in the
# Secret — this chart matches that pattern: `auth.database` is rendered as a
# plain `value:` env, not a secretKeyRef).
auth:
  existingSecret: myapp-postgresql-db-secret
  secretKeys:
    user: DB_USERNAME
    password: POSTGRES_PASSWORD
  database: myapp

persistence:
  existingClaim: myapp-postgresql-db-pvc

service:
  type: NodePort
  nodePort: 30632

# When the legacy raw YAML used logging_collector=on with /var/log/postgresql.
logCollector:
  enabled: true

Adoption checklist before helm upgrade --install:

KCTX=<your-context>
NS=myapp-db-redis

# 1. Annotate existing resources for Helm ownership
for kind in pvc/myapp-postgresql-db-pvc \
            secret/myapp-postgresql-db-secret \
            configmap/myapp-postgresql-db-config \
            service/myapp-postgresql-db; do
  kubectl --context $KCTX -n $NS annotate "$kind" \
    meta.helm.sh/release-name=myapp-postgresql-db \
    meta.helm.sh/release-namespace=$NS --overwrite
  kubectl --context $KCTX -n $NS label "$kind" \
    app.kubernetes.io/managed-by=Helm --overwrite
done

# 2. (Optional) belt-and-suspenders against accidental future helm uninstall
kubectl --context $KCTX -n $NS annotate pvc myapp-postgresql-db-pvc \
  helm.sh/resource-policy=keep --overwrite

# 3. Drop the legacy Deployment so Helm can recreate with new selector
kubectl --context $KCTX -n $NS delete deployment myapp-postgresql-db --wait

# 4. helm install. After install, remove stale `app:` key from Service
#    selector that helm's client-side merge left behind:
kubectl --context $KCTX -n $NS patch svc myapp-postgresql-db \
  --type=json -p='[{"op":"remove","path":"/spec/selector/app"}]'

4. Backup CronJob — daily pg_dump

The job checks its own output before it counts as done: pg_dump writes a terminating comment as the last line of a plain-SQL dump, so the CronJob greps the tail for it and deletes the file and fails the Job when it is missing. set -e alone does not cover this — a dump cut short by a full disk, a dropped connection or an OOM kill still exits 0 and leaves a plausible-looking .sql behind, and the truncation is then discovered at restore time, which is the one moment it cannot be fixed.

A failed run leaves nothing on the volume either. The output redirect creates the file before pg_dump writes a byte, so a dump that fails outright — a client/server version mismatch, a refused connection, a bad credential — would otherwise leave a 0-byte .sql that reads as real when listing the directory. Cleanup runs from a trap, disarmed only once the dump has passed verification — and disarmed before retention runs, so it can never delete the dump just taken.

auth:
  user: myapp
  password: changeme
  database: myapp
backup:
  enabled: true
  schedule: "0 18 * * *"        # 03:00 KST = 18:00 UTC
  retentionDays: 30
  persistence:
    enabled: true
    storageClass: nfs-client
    size: 50Gi

When auth.database is set, the CronJob runs pg_dump <db>. When empty, it runs pg_dumpall. Backups are written to /backup-data/postgres-<db|all>-<YYYYMMDD>.sql; files older than retentionDays are pruned each run.

Trigger an ad-hoc run:

kubectl -n myapp-db-redis create job \
  --from=cronjob/myapp-postgresql-db-backup \
  myapp-postgresql-db-backup-manual-$(date +%Y%m%d-%H%M)

5. Private registry — chart-managed pull Secret

imagePullSecret:
  create: true
  dockerconfigjson: <base64 ~/.docker/config.json>
image:
  repository: harbor.example.com/library/postgres
  tag: "16-alpine"

Values reference

Naming + adoption

KeyDefaultDescription
nameOverride""overrides app.kubernetes.io/name label
fullnameOverride""overrides the base name for Deployment / Service / default PVC / default Secret / default ConfigMap
configMap.nameOverride""overrides only the ConfigMap name (default <fullname>-config)

Image

KeyDefaultDescription
image.repositorypostgrescontainer image repository
image.tag"" (= Chart.AppVersion, currently 18-alpine)tag override
image.pullPolicyIfNotPresent
imagePullSecrets[][]bring-your-own pull Secrets, additive
imagePullSecret.createfalserender a dockerconfigjson Secret
imagePullSecret.name"" (= <fullname>-pull-secret)name override
imagePullSecret.dockerconfigjson""base64-encoded ~/.docker/config.json

Service

KeyDefaultDescription
service.typeClusterIPone of ClusterIP / NodePort / LoadBalancer
service.port5432
service.nodePortnullrequired when service.type=NodePort and you want a fixed port
service.annotations{}merged with commonAnnotations

Persistence

KeyDefaultDescription
persistence.enabledtruewhen false, mounts an emptyDir for /var/lib/postgresql/data (dev only)
persistence.storageClass""empty = cluster default
persistence.accessModes[ReadWriteOnce]
persistence.size20Gi
persistence.existingClaim""when set, chart skips PVC rendering and the Pod mounts this PVC
persistence.annotations{}merged with commonAnnotations
pgData/var/lib/postgresql/data/pgdataPGDATA env — initdb writes here (subdir of volume mount avoids lost+found collision on some storageclasses)

Authentication

KeyDefaultDescription
auth.user""required when existingSecret is empty
auth.password""required when existingSecret is empty
auth.database""optional. When set, POSTGRES_DB env is rendered as a plain value: (not from Secret) — DB name is not sensitive
auth.existingSecret""when set, chart skips Secret rendering
auth.secretKeys.userPOSTGRES_USERsecret key the container reads POSTGRES_USER from
auth.secretKeys.passwordPOSTGRES_PASSWORDsecret key for POSTGRES_PASSWORD

Postgres configuration

KeyDefaultDescription
customConfig.postgresqlConftuned generic settingsrendered into ConfigMap as postgresql.conf
customConfig.pgHbaConflocal trust + md5 over IPrendered into ConfigMap as pg_hba.conf
useCustomConfigtruewhen true, container starts with -c config_file=… + -c hba_file=… pointing at the mounted ConfigMap
logCollector.enabledfalsemount an emptyDir for logging_collector = on log files
logCollector.mountPath/var/log/postgresql

Changing customConfig or the credentials restarts the Pod, by design: the Deployment carries checksum/config and checksum/secret pod annotations so a config or credential change actually reaches the running server. The strategy is Recreate, so that restart is a short outage rather than a rolling swap — batch config edits rather than applying them one at a time.

Those checksums hash only the ConfigMap data and the Secret stringData, never the rendered objects as a whole. Hashing the whole object would fold in the helm.sh/chart label, which carries the chart version, and every chart upgrade would then restart the database whether or not anything it runs on had changed.

Pod scheduling + resources

KeyDefaultDescription
resources.requests.cpu100m
resources.requests.memory256Mi
resources.limits.cpu1000m
resources.limits.memory2Gi
nodeSelector / tolerations / affinity / topologySpreadConstraints / priorityClassNameemptystandard pod scheduling knobs
podSecurityContext / securityContext{}
livenessProbe / readinessProbe{}empty by default to avoid initdb race; enable after first install

Backup CronJob

KeyDefaultDescription
backup.enabledfalse
backup.schedule"0 18 * * *"cron in cluster timezone
backup.concurrencyPolicyForbid
backup.successfulJobsHistoryLimit3
backup.failedJobsHistoryLimit3
backup.retentionDays30files older than this are pruned
backup.image.{repository,tag,pullPolicy}inherits from image.* when emptyoverride to pin a different pg_dump client image
backup.resources{}
backup.persistence.*RWO 20Gidedicated PVC for backups

Escape hatches

KeyDefaultDescription
commonLabels / commonAnnotations{}applied to every resource
resourceMetadata.<resource>.{labels,annotations}{}per-resource override
specExtra{}merged into Deployment.spec
podTemplateExtra{}merged into PodTemplateSpec.spec
kubernetesExtra{}each value rendered as an additional manifest in this release
serviceAccount.{create,name,annotations,imagePullSecrets,automountServiceAccountToken}create=falsescope-pinned SA
networkPolicy.{enabled,policyTypes,ingress,egress,podSelector}enabled=falsenative networking.k8s.io/v1 shape

License

Apache-2.0

Deploy postgresql with OpenTenant

Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has postgresql 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 chartpostgresql is pinned at v0.1.5 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