Skip to content

PostgreSQL production setup on k3s

Overview

This document describes the production PostgreSQL setup for the Johor Zoo ticketing system running on a 3-node k3s cluster.


Architecture

Your App
   ↓
PgBouncer Pooler (postgres-pooler-rw)
   ↓
CNPG Cluster
   ├── postgres-cluster-1  (primary)
   ├── postgres-cluster-2  (replica)
   └── postgres-cluster-3  (replica)
        ↓
local-path-retain StorageClass
   └── local disk on each node (no Longhorn — CNPG handles replication)

Why This Architecture

Concern Solution
High Availability CNPG manages 1 primary + 2 replicas with auto-failover
Storage local-path-retain — no Longhorn needed since CNPG already replicates data
Connection Pooling PgBouncer in transaction mode — reuses connections to reduce Postgres load
Data Safety Retain reclaim policy — PVs survive PVC deletion

Note: Longhorn replication is intentionally not used for Postgres because CNPG already replicates data across all 3 nodes. Using both would be wasteful (9 copies of data instead of 3).


Prerequisites

All 3 Nodes

open-iscsi must be enabled:

sudo systemctl enable iscsid
sudo systemctl start iscsid

multipathd must be configured to ignore Longhorn virtual disks:

sudo bash -c 'cat >> /etc/multipath.conf << EOF

blacklist {
    device {
        vendor  "IET"
        product "VIRTUAL-DISK"
    }
}
EOF'
sudo systemctl restart multipathd

Cluster

  • k3s 3-node cluster (ticket-node-1, ticket-node-2, ticket-node-3)
  • CloudNativePG operator installed in cnpg-system namespace

Installation

1. Install CloudNativePG Operator

helm repo add cnpg https://cloudnative-pg.github.io/charts
helm repo update
helm upgrade --install cnpg cnpg/cloudnative-pg \
  --namespace cnpg-system --create-namespace

2. Apply Manifests

Apply in order:

kubectl apply -f 00-namespace.yaml
kubectl apply -f 01-storageclass.yaml
kubectl apply -f 02-secret-superuser.yaml
kubectl apply -f 03-secret-appuser.yaml
kubectl apply -f 04-cluster.yaml

# Wait for cluster to be healthy
kubectl get cluster -n db --watch

# Then apply pooler and monitor
kubectl apply -f 05-pooler.yaml
kubectl apply -f 06-podmonitor.yaml

File Reference

File Purpose
00-namespace.yaml Creates db namespace
01-storageclass.yaml local-path-retain StorageClass
02-secret-superuser.yaml Postgres superuser secret (operator use only)
03-secret-appuser.yaml App user secret (johorZoo_admin)
04-cluster.yaml CNPG cluster — 3 instances, 40Gi each
05-pooler.yaml PgBouncer pooler — 2 instances, transaction mode
06-podmonitor.yaml PodMonitor for Prometheus/Vector scraping

Database Details

Property Value
Database johorZoo
Schema johorzoo
App User johorZoo_admin
Default search_path johorzoo
Storage 40Gi per instance
Postgres version 16

Connection String

Always connect via PgBouncer, never directly to Postgres:

host:     postgres-pooler-rw.db.svc.cluster.local
port:     5432
dbname:   johorZoo
user:     johorZoo_admin

Data Migration

Run once after cluster is healthy:

# Copy SQL file into primary pod
kubectl cp /path/to/backup_postgres.sql \
  db/postgres-cluster-1:/var/lib/postgresql/data/init.sql

# Run migration
kubectl exec -n db postgres-cluster-1 -- \
  psql -U postgres -d johorZoo -f /var/lib/postgresql/data/init.sql

# Run additional migrations with search path
kubectl exec -n db postgres-cluster-1 -- \
  psql -U postgres -d johorZoo \
  -c "SET search_path TO johorzoo" \
  -f /var/lib/postgresql/data/migration.sql

Useful Commands

# Check cluster status
kubectl get cluster -n db

# Check all pods
kubectl get pods -n db

# Check which pod is primary
kubectl get pods -n db -l cnpg.io/cluster=postgres-cluster

# Check pooler
kubectl get pooler -n db

# Check PVCs
kubectl get pvc -n db

# Connect to primary as superuser
kubectl exec -n db postgres-cluster-1 -- psql -U postgres

# List tables
kubectl exec -n db postgres-cluster-1 -- \
  psql -U postgres -d johorZoo \
  -c "SELECT tablename FROM pg_tables WHERE schemaname = 'johorzoo';"

# Check active connections
kubectl exec -n db postgres-cluster-1 -- \
  psql -U postgres -c "SELECT count(*) FROM pg_stat_activity;"

# Expand storage (if needed)
# Edit 04-cluster.yaml → change storage.size
kubectl apply -f 04-cluster.yaml

Longhorn Maintenance

Snapshot Cleanup (automated)

A recurring job runs daily at 2am to clean up orphaned snapshots. Apply once:

kubectl apply -f - <<'EOF'
apiVersion: longhorn.io/v1beta2
kind: RecurringJob
metadata:
  name: snapshot-cleanup
  namespace: longhorn-system
spec:
  name: snapshot-cleanup
  cron: "0 2 * * *"
  task: snapshot-cleanup
  groups:
    - default
  retain: 0
  concurrency: 1
  labels: {}
EOF

Verify it was created:

kubectl get recurringjobs -n longhorn-system

Note: task: snapshot-cleanup with retain: 0 purges all orphaned snapshots daily at 2am. This prevents snapshot buildup which can fill node disks over time.

Manual Snapshot Purge via API

If snapshots are stuck:

# Port-forward Longhorn UI
kubectl port-forward -n longhorn-system svc/longhorn-frontend 8080:80

# Trigger purge
curl -s -X POST http://localhost:8080/v1/volumes/<volume-id>?action=snapshotPurge

Check Node Disk Usage

for node in ticket-node-1 ticket-node-2 ticket-node-3; do
  echo "=== $node ==="
  ssh pentadbir@$node df -h /data/longhorn
done

Check Scheduled Storage Per Node

kubectl get nodes.longhorn.io ticket-node-1 -n longhorn-system \
  -o jsonpath='{.status.diskStatus.disk-1.storageScheduled}'

Loki Retention Fix

Loki retention was not working due to deprecated table_manager config. Fixed by removing:

# REMOVED — was overriding compactor retention
table_manager:
  retention_deletes_enabled: false

Compactor now handles retention automatically with retention_period: 14d.

To manually clean old chunks:

kubectl exec -n logging loki-<pod> -- find /tmp/loki/chunks -type f -mtime +14 -delete


Known Issues & Solutions

Issue Cause Solution
Longhorn volume faulted multipathd interfering with iSCSI Add IET/VIRTUAL-DISK to multipath blacklist
PVC stuck in Pending Not enough schedulable storage on node Clean stale replicas, delete orphaned Longhorn volumes
Snapshot not purging Volume detached Use Longhorn API snapshotPurge action
johorZoo_admin peer auth failed CNPG peer auth restriction Use postgres superuser for admin tasks
Schema not found PostgreSQL lowercases names Use johorzoo (lowercase) not johorZoo