Files
Kubernetes/PostgreSQL/MIGRATION_RUNBOOK.md
T

13 KiB
Raw Blame History

PostgreSQL Migration Runbook

Migrate the postgres database from the old StatefulSet (local-storage, image pgvector/pgvector:pg18-trixie) to a new Deployment postgres-hetzner on hcloud-volumes (Hetzner CSI), using the public image pgvector/pgvector:pg18-trixie (Postgres 18 + pgvector 0.8.2).

Strategy: logical dump/restore via pg_dumpall, Option A service repoint (external IP 10.2.0.122 and internal DNS postgres.database.svc.cluster.local both unchanged → outside dependency and in-cluster consumers need no reconfiguration).

Downtime: required (writers stopped during dump/restore). Estimated window: ~20–40 min depending on 18 GB transfer speed.


Current state (verified in cluster)

Old DB

  • StatefulSet postgres in namespace database (120 days old).
  • Pod postgres-0 on node woker-1-8gb-hel1-1, IP 10.0.2.116.
  • Image: pgvector/pgvector:pg18-trixie (Postgres 18 + pgvector).
  • Credentials: hardcoded POSTGRES_USER=admin, POSTGRES_PASSWORD=jd@wXseh9z7vM@9. Also stored in Secret postgres-secret (namespace database) with the same values.
  • PVC postgres-data-postgres-0 (from STS volumeClaimTemplates): local-storage, 30Gi requested, bound to PV example-pv (50Gi).

Services (two)

  1. postgres — ClusterIP 10.107.200.144, selector app: postgres. Internal DNS postgres.database.svc.cluster.local used by in-cluster consumers.
  2. postgres-service — LoadBalancer, external IP 10.2.0.122 (annotation lbipam.cilium.io/ips: 10.2.0.122, pool postgres-pool CIDR 10.2.0.0/24), selector app: postgres. Used by the outside dependency.

Cilium LB IP pools

  • lan-pool → 10.1.0.101–10.1.0.199 (94 free) — used by Cilium ingresses.
  • postgres-pool → 10.2.0.0/24 (255 free, 1 used = 10.2.0.122) — dedicated postgres pool.

Databases to migrate (~18.4 GB total)

Database Size Owner Used by
homeassistant 18 GB homeassistant outside dependency (via LB 10.2.0.122)
immich 445 MB admin immich-server, immich-machine-learning
gitea 15 MB gitea gitea
grafana 14 MB grafana grafana
backup 8.5 MB data_mover (legacy)
admin 7.7 MB admin —

immich DB extensions (must be present in new image)

cube, earthdistance, pg_trgm, unaccent, uuid-ossp, vector (0.8.2), plpgsql. All present in the custom image (postgres:18.4 + pgvector v0.8.2) and in pgvector/pgvector:pg18-trixie.

Consumers of postgres.database.svc.cluster.local (all unchanged with Option A)

Consumer Namespace Deployment
immich-server immich immich-server
immich-machine-learning immich immich-machine-learning
gitea gitea gitea
grafana monitoring grafana

External consumer

  • The outside dependency connects via the old pod IP 10.0.2.116 (NOT the LB 10.2.0.122). This was incorrect — pod IPs are ephemeral and disappear when the pod is deleted.
  • After migration, the old pod IP 10.0.2.116 is gone. The outside dependency must be reconfigured to use 10.2.0.122:5432 (the stable LB IP, which routes to the new postgres-hetzner pod).
  • The LB postgres-service keeps IP 10.2.0.122 via the Cilium annotation lbipam.cilium.io/ips: 10.2.0.122 (pool postgres-pool) — this IP is stable across pod restarts/replacements.
  • Action required: update the outside dependency's DB host from 10.0.2.116 → 10.2.0.122 before/after cutover.

Repo manifest changes (already applied)

  • PostgreSQL/postgress_deplay.yaml — synced to live STS (rollback reference).
  • PostgreSQL/postgres_service.yaml — ClusterIP postgres, selector app: postgres-hetzner.
  • PostgreSQL/postgres_lb_service.yaml (new) — LB postgres-service, static IP 10.2.0.122, selector app: postgres-hetzner.
  • PostgreSQL/hetzner/postgres_hetzner_deployment.yaml — uses postgres-secret (secretKeyRef), public image pgvector/pgvector:pg18-trixie (custom image 10.0.2.119:5000/custom-postgres:latest not reachable — old node IP gone; nodes now on 10.1.0.x and cluster DNS not resolvable from node containerd), strategy: Recreate.
  • Removed stale postgres_pvc.yaml and postgres_static_endpoint.yaml.

Execution

Phase 0 — Pre-flight (re-run on migration day to confirm no drift)

kubectl get pvc -n database
kubectl get sts,deploy,svc,pod,endpointslice -n database
kubectl exec -n database postgres-0 -- psql -U admin -d postgres -c '\l+'
kubectl get svc postgres-service -n database -o jsonpath='{.status.loadBalancer.ingress[0].ip}'   # expect 10.2.0.122
# Confirm new objects don't exist yet
kubectl get deploy postgres-hetzner -n database     # expect NotFound
kubectl get pvc postgres-hetzner-pvc -n database     # expect NotFound

Phase 1 — Stand up new empty DB (no downtime yet)

kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_pvc.yaml
kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_secret.yml
kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_deployment.yaml
kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_service.yaml     # temp internal svc for restore
kubectl rollout status deploy/postgres-hetzner -n database
kubectl get pod -n database -l app=postgres-hetzner -w                # wait Running

Phase 2 — Downtime begins, stop ALL writers

kubectl scale deploy/immich-server -n immich --replicas=0
kubectl scale deploy/immich-machine-learning -n immich --replicas=0
kubectl scale deploy/gitea -n gitea --replicas=0
kubectl scale deploy/grafana -n monitoring --replicas=0
# >>> STOP the outside dependency writing to homeassistant DB now <<<

# confirm all stopped
kubectl get pod -n immich -l app=immich-server
kubectl get pod -n immich -l app=immich-machine-learning
kubectl get pod -n gitea -l app=gitea
kubectl get pod -n monitoring -l app=grafana

Phase 3 — Dump + restore (writers down = consistent ~18.4 GB)

IMPORTANT: Do NOT use pg_dumpall | psql over a kubectl exec pipe. The kubectl websocket times out on large transfers (~18 GB) and the text format corrupts vector data (long embedding strings get truncated, breaking smart_search and other pgvector tables). Use binary pg_dump -Fc with pg_restore, running pg_dump from inside the new pod pointing at the old DB via the postgres Service.

OLD=$(kubectl get pod -n database -l app=postgres -o jsonpath='{.items[0].metadata.name}')
NEW=$(kubectl get pod -n database -l app=postgres-hetzner -o jsonpath='{.items[0].metadata.name}')
echo "OLD=$OLD NEW=$NEW"

# Step 1: pg_dumpall for roles + small DBs (admin, backup, postgres, gitea, grafana) via text pipe
#         — these have no vector data and are small (<15 MB each), safe over kubectl pipe.
kubectl exec -n database $OLD -- pg_dumpall -c -U admin --roles-only \
  | kubectl exec -i -n database $NEW -- psql -U admin -d postgres
# Create the small databases (gitea, grafana, backup, homeassistant) — schema only first if needed,
# or rely on pg_dumpall to recreate them. For non-immich DBs, text pipe is fine (no vector columns):
kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d gitea -f /tmp/gitea.dump
kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d grafana -f /tmp/grafana.dump
kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d backup -f /tmp/backup.dump
kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d homeassistant -f /tmp/homeassistant.dump
# Transfer each dump from old pod to new pod using pg_dump from the new pod (binary-safe, avoids kubectl pipe):
for db in gitea grafana backup homeassistant immich; do
  kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \
    pg_dump -h postgres.database.svc.cluster.local -U admin -d $db -Fc -f /tmp/$db.dump
done

# Step 2: restore each DB on the new pod (drop existing first if re-running)
for db in gitea grafana backup homeassistant immich; do
  kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \
    psql -h localhost -U admin -d postgres -c "DROP DATABASE IF EXISTS $db;"
  kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \
    psql -h localhost -U admin -d postgres -c "CREATE DATABASE $db OWNER admin;"
  kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \
    pg_restore -h localhost -U admin -d $db --no-owner --no-privileges /tmp/$db.dump
done

# Step 3: verify DBs + sizes
kubectl exec -n database $NEW -- psql -U admin -d postgres -c '\l+'
# verify immich extensions
kubectl exec -n database $NEW -- psql -U admin -d immich -c "\dx"
# spot-check row counts
kubectl exec -n database $NEW -- psql -U admin -d immich -c "SELECT count(*) FROM asset;"
kubectl exec -n database $NEW -- psql -U admin -d immich -c "SELECT count(*) FROM smart_search;"
kubectl exec -n database $NEW -- psql -U admin -d homeassistant -c "SELECT count(*) FROM events;"
kubectl exec -n database $NEW -- psql -U admin -d gitea -c "SELECT count(*) FROM repository;"
kubectl exec -n database $NEW -- psql -U admin -d grafana -c "SELECT count(*) FROM dashboard;"

# Step 4: cleanup dump files
for db in gitea grafana backup homeassistant immich; do
  kubectl exec -n database $NEW -- rm -f /tmp/$db.dump
  kubectl exec -n database $OLD -- rm -f /tmp/$db.dump 2>/dev/null
done

Why dump from the new pod: the new pod can reach the old DB via postgres.database.svc.cluster.local (still pointing at old pods until cutover), and writes the binary dump file directly to its own PVC — no kubectl pipe, no truncation, no websocket timeout.

Phase 4 — Cutover (repoint both Services to new pods)

kubectl apply -f PostgreSQL/postgres_service.yaml          # ClusterIP postgres → app: postgres-hetzner
kubectl apply -f PostgreSQL/postgres_lb_service.yaml       # LB postgres-service → app: postgres-hetzner, IP 10.2.0.122 kept

kubectl get svc postgres postgres-service -n database
# verify external IP still 10.2.0.122
kubectl get svc postgres-service -n database -o jsonpath='{.status.loadBalancer.ingress[0].ip}'

# verify in-cluster connectivity via the unchanged DNS name
kubectl run pg-test --rm -it --image=postgres:18 --restart=Never -- \
  psql -h postgres.database.svc.cluster.local -U admin -d postgres -c '\l+'

Phase 5 — Restart consumers (immich's initContainer pg_isready validates)

kubectl scale deploy/immich-server -n immich --replicas=1
kubectl scale deploy/immich-machine-learning -n immich --replicas=1
kubectl scale deploy/gitea -n gitea --replicas=1
kubectl scale deploy/grafana -n monitoring --replicas=1

kubectl rollout status deploy/immich-server -n immich
kubectl rollout status deploy/gitea -n gitea
kubectl rollout status deploy/grafana -n monitoring

kubectl logs deploy/immich-server -n immich --tail=50      # no DB errors
kubectl logs deploy/gitea -n gitea --tail=50
# >>> restart the outside dependency (now pointed at 10.2.0.122) <<<

Phase 6 — Cleanup (after a few days green; KEEP old PVC as rollback first)

kubectl delete sts postgres -n database --cascade=orphan   # orphan keeps pods/PVC for rollback
kubectl delete svc postgres-hetzner -n database            # temp restore svc

# DO NOT delete PVC postgres-data-postgres-0 yet — rollback safety net (~1 week)

# After confidence period:
kubectl delete pod -n database -l app=postgres             # leftover orphan pod
kubectl delete pvc postgres-data-postgres-0 -n database

Rollback (if Phase 4/5 fails — recovers OLD DB)

Caveat: rollback loses any writes made to the new DB after cutover (old PVC was not updated by dump/restore). This is inherent to logical dump/restore migration. If you need zero-data-loss rollback, the migration must use logical replication instead — request that redesign separately.

# Repoint both Services back to old pods
kubectl patch svc postgres -n database --type=json \
  -p='[{"op":"replace","path":"/spec/selector","value":{"app":"postgres"}}]'
kubectl patch svc postgres-service -n database --type=json \
  -p='[{"op":"replace","path":"/spec/selector","value":{"app":"postgres"}}]'

# Scale consumers back up — they hit old DB again
kubectl scale deploy/immich-server -n immich --replicas=1
kubectl scale deploy/immich-machine-learning -n immich --replicas=1
kubectl scale deploy/gitea -n gitea --replicas=1
kubectl scale deploy/grafana -n monitoring --replicas=1
# >>> restart the outside dependency (pointed at 10.2.0.122) <<<

If rollback happens before Phase 6 cleanup, the old STS + PVC postgres-data-postgres-0 are intact and the old DB serves immediately. If rollback happens after kubectl delete sts postgres --cascade=orphan, recreate the STS from PostgreSQL/postgress_deplay.yaml (the orphan pod + PVC are reused because the STS name + selector match).


Pre-migration checklist (outside dependency)

Before starting Phase 1, ensure:

  • Outside dependency DB host updated from 10.0.2.116 → 10.2.0.122 (the old pod IP is gone; the LB IP 10.2.0.122 is stable and routes to the new DB).
  • Outside dependency that writes to homeassistant DB via 10.2.0.122 can be stopped for the maintenance window.
  • Backup of any critical external state taken.
  • Maintenance window scheduled.

Pre-migration checklist (cluster)

  • kubectl get pvc -n database shows postgres-data-postgres-0 Bound on local-storage.
  • postgres-service LB external IP is 10.2.0.122.
  • All consumer Deployments exist and are Ready (immich-server, immich-machine-learning, gitea, grafana).
  • No postgres-hetzner Deployment/PVC exist yet.