Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 16: CNPG: Hochverfügbarkeit

Ziel: Du misst, wie lange pg-notes bei Pod-, Node-Ausfall, Switchover und Wartung nicht schreibbar ist, schaltest synchrone Replikation und Fencing, rollst Konfiguration und Minor-Update aus und hebst einen Cluster von 17 auf 18. · Dauer: ca. 90 min · Voraussetzung: Tag 10, Tag 15

Briefing

  • Failover: ungeplant, der Operator befördert die Replica mit dem neuesten LSN. Switchover: geplant, erst sauber herunterfahren, dann befördern.
  • Messlatte ist nicht „Pod läuft“, sondern: Wie lange schlagen INSERTs fehl?
  • Jede Änderung, die einen Neustart braucht, rollt CNPG aus: Replicas zuerst, der Primary zuletzt – per Neustart oder Switchover (primaryUpdateMethod).
  • Major-Upgrade geht seit CNPG 1.26 in-place mit pg_upgrade --link – offline.
mkdir -p ~/pg/tag16 && cp ~/.kube/config ~/pg/tag16/.kc
export KUBECONFIG=~/pg/tag16/.kc
kubectl create namespace tag16

Drill 1: Messgerät aufbauen

Ein Pod schreiber fügt alle 0,2 s eine Zeile ein; Zeitstempel und Server-IP schreibt die Datenbank selbst. Lücken in der Tabelle = Ausfallzeit. Den Client-Pod aus Tag 14 brauchst du zum Auswerten:

kubectl apply -f ~/pg/tag14/psql-client.yaml
kubectl wait --for=condition=Ready pod/psql-client -n tag14
kubectl exec -n tag14 psql-client -- psql -c "CREATE TABLE ha_test (
  id bigserial PRIMARY KEY, t timestamptz NOT NULL DEFAULT clock_timestamp(),
  srv inet DEFAULT inet_server_addr())"
cat > ~/pg/tag16/schreiber.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: schreiber
  namespace: tag14
spec:
  containers:
  - name: psql
    image: ghcr.io/cloudnative-pg/postgresql:18.7-minimal-trixie
    command:
    - sh
    - -c
    - while true; do psql -Atqc "INSERT INTO ha_test DEFAULT VALUES"; sleep 0.2; done
    env:
    - name: PGCONNECT_TIMEOUT
      value: "2"
    - name: PGHOST
      valueFrom: {secretKeyRef: {name: pg-notes-app, key: host}}
    - name: PGDATABASE
      valueFrom: {secretKeyRef: {name: pg-notes-app, key: dbname}}
    - name: PGUSER
      valueFrom: {secretKeyRef: {name: pg-notes-app, key: username}}
    - name: PGPASSWORD
      valueFrom: {secretKeyRef: {name: pg-notes-app, key: password}}
    resources:
      requests: {cpu: 10m, memory: 16Mi}
      limits: {memory: 64Mi}
EOF
kubectl apply -f ~/pg/tag16/schreiber.yaml

Erwartet:

pod/psql-client created
pod/psql-client condition met
CREATE TABLE
pod/schreiber created

Die Auswertung brauchst du in jedem Drill – zwei Abfragen, vorher jeweils TRUNCATE ha_test:

kubectl exec -n tag14 psql-client -- psql -c "SELECT srv, count(*),
  min(t)::time(1), max(t)::time(1) FROM ha_test GROUP BY srv ORDER BY 3" \
  -c "SELECT t::time(1) AS nach, gap FROM (SELECT t, t - lag(t) OVER (ORDER BY t)
  AS gap FROM ha_test) x ORDER BY gap DESC NULLS LAST LIMIT 1"

Achtung: Kein kubectl exec … while … als Schreibschleife: exec läuft über das Kubelet. Fällt in Drill 3 das Kubelet aus, bricht die Sitzung mit websocket: close 1006 ab – und die Messung mit ihr.

Fortschritt speichern? Kostenlos registrieren

Drill 2: Failover bei Pod-Ausfall

kubectl exec -n tag14 psql-client -- psql -qc 'TRUNCATE ha_test'
kubectl get cluster pg-notes -n tag14
P=$(kubectl get cluster pg-notes -n tag14 -o jsonpath='{.status.currentPrimary}')
kubectl delete pod $P -n tag14 --wait=false
while sleep 2; do echo "$(date +%T) $(kubectl get cluster pg-notes -n tag14 \
  -o jsonpath='{.status.currentPrimary} {.status.phase}')"; done | uniq -f1

Nach etwa 20 s Strg+C, dann die Auswertung.

Erwartet (gekürzt; deine Pod-Namen, IPs und Timeline können abweichen):

NAME       AGE   INSTANCES   READY   STATUS                     PRIMARY
pg-notes   45m   3           3       Cluster in healthy state   pg-notes-1
pod "pg-notes-1" deleted from tag14 namespace
05:36:13 pg-notes-1 Cluster in healthy state
05:36:15 pg-notes-1 Failing over
05:36:25 pg-notes-3 Failing over
05:36:27 pg-notes-3 Waiting for the instances to become active
    srv    | count |    min     |    max
-----------+-------+------------+------------
 10.0.1.54 |    14 | 05:36:08.3 | 05:36:13.8
 10.0.1.57 |    60 | 05:36:25.7 | 05:36:53.4
    nach    |       gap
------------+-----------------
 05:36:25.7 | 00:00:11.887219

Rund 12 s keine Schreibzugriffe. kubectl logs schreiber -n tag14 zeigt die Fehler der Lücke: FATAL: the database system is shutting down, dann Connection refused, bis -rw auf den neuen Primary zeigt.

Fortschritt speichern? Kostenlos registrieren

Drill 3: Failover bei Node-Ausfall

Ein toter Node meldet nichts mehr. Simuliert: Kubelet stoppen und den postgres-Container hart beenden. Auf cp1:

kubectl exec -n tag14 psql-client -- psql -qc 'TRUNCATE ha_test'
P=$(kubectl get cluster pg-notes -n tag14 -o jsonpath='{.status.currentPrimary}')
N=$(kubectl get pod $P -n tag14 -o jsonpath='{.spec.nodeName}')
NIP=$(kubectl get node $N -o jsonpath='{.status.addresses[0].address}')
echo $P $N $NIP
kubectl get pods -n tag14 -o wide | grep pg-notes

Erwartet (gekürzt; deine Pod-Namen, IPs und Timeline können abweichen):

pg-notes-2 worker2 172.16.0.83
pg-notes-1    2/2     Running   0     ...   worker1   ...
pg-notes-2    2/2     Running   2     ...   worker2   ...
pg-notes-3    2/2     Running   0     ...   worker1   ...

Der Primary ist allein auf seinem Node – genau dieser Fall ist hier gewollt (zum Gegenfall gleich mehr):

ssh $NIP "sudo systemctl stop kubelet && sudo crictl stop \
  \$(sudo crictl ps --name '^postgres\$' --label io.kubernetes.pod.name=$P -q)"
while sleep 3; do echo "$(date +%T) $(kubectl get cluster pg-notes -n tag14 \
  -o jsonpath='{.status.currentPrimary} {.status.phase}')"; done | uniq -f1

Erwartet (gekürzt, nach etwa 90 s Strg+C; Namen können abweichen):

29450d03f010...
05:47:05 pg-notes-2 Cluster in healthy state
05:47:55 pg-notes-2 Failing over
05:48:17 pg-notes-1 Failing over

Rund 50 s passiert nichts: So lange wartet Kubernetes, bis der Node NotReady ist und die Pods dort Ready=False werden. Erst dann befördert der Operator. Die Phase bleibt Failing over, bis der alte Primary wieder erreichbar ist. Die Auswertung läuft jetzt über eine Instanz auf dem gesunden Node (psql-client liegt evtl. auf dem toten):

kubectl exec -n tag14 pg-notes-1 -c postgres -- psql -d notes \
  -c "SELECT t::time(1) AS nach, gap FROM (SELECT t, t - lag(t) OVER (ORDER BY t)
  AS gap FROM ha_test) x ORDER BY gap DESC NULLS LAST LIMIT 1" \
  -c 'SELECT timeline_id FROM pg_control_checkpoint()'
ssh $NIP sudo systemctl start kubelet

Erwartet (gekürzt; deine Timeline kann abweichen):

    nach    |       gap
------------+-----------------
 05:48:19.7 | 00:01:14.471558
 timeline_id
-------------
           6

1:14 min ohne Schreibzugriff. Nach dem Start des Kubelets kommt der alte Primary nach rund 20 s als Replica zurück (Cluster in healthy state).

Achtung: Liegen Primary und eine Replica auf dem toten Node, wartet CNPG länger. Das Operator-Log zeigt dann nur Cannot extract Pod status und Waiting for the Kubelet to refresh the readiness probe – es kann den LSN der verlorenen Replica nicht prüfen. Erst wenn Kubernetes die Pods nach 5 min (tolerationSeconds: 300) räumt, folgt der Failover. Im Labor: 6:18 min Lücke. Mit nur zwei Workern ist das unvermeidbar; in Produktion gehören drei Instanzen auf drei Nodes.

Fortschritt speichern? Kostenlos registrieren

Drill 4: Switchover

Geplanter Wechsel, etwa vor Wartung:

kubectl exec -n tag14 psql-client -- psql -qc 'TRUNCATE ha_test'
kubectl cnpg promote pg-notes pg-notes-2 -n tag14
kubectl cnpg status pg-notes -n tag14 | grep -E 'Primary instance|Timeline'

Erwartet (gekürzt, Auswertung nach etwa 30 s):

Node pg-notes-2 in cluster pg-notes will be promoted
Primary instance:        pg-notes-2
Current Write LSN:       0/1000DAE8 (Timeline: 7 - WAL File: 000000070000000000000010)
    srv     | count |    min     |    max
------------+-------+------------+------------
 10.0.1.145 |     9 | 05:50:24.4 | 05:50:27.8
 10.0.2.14  |    49 | 05:50:40.5 | 05:51:02.2
    nach    |       gap
------------+-----------------
 05:50:40.5 | 00:00:12.758206

Auch ein Switchover kostet hier rund 13 s: alter Primary fährt herunter (fast, Zeitlimit switchoverDelay), die Replica holt das letzte WAL ab, wird befördert, -rw wird umgebogen. Dafür geht kein bestätigter Commit verloren. Die Timeline steigt bei jedem Wechsel.

Fortschritt speichern? Kostenlos registrieren

Drill 5: Synchrone Replikation und Fencing

synchronous_standby_names darfst du nicht selbst setzen; das macht postgresql.synchronous:

kubectl patch cluster pg-notes -n tag14 --type merge \
  -p '{"spec":{"postgresql":{"synchronous":{"method":"any","number":1}}}}'
kubectl cnpg psql pg-notes -n tag14 -- -Atc 'SHOW synchronous_standby_names' \
  -c 'SELECT application_name, sync_state FROM pg_stat_replication ORDER BY 1'

Erwartet (nach etwa 15 s, ohne Neustart):

cluster.postgresql.cnpg.io/pg-notes patched
ANY 1 ("pg-notes-1","pg-notes-3","pg-notes-2")
pg-notes-1|quorum
pg-notes-3|quorum

any = Quorum: Ein Commit wartet, bis eine beliebige Replica das WAL hat. Fencing hält PostgreSQL in einer Instanz an, der Pod bleibt zum Untersuchen stehen. Beide Replicas einzäunen:

kubectl cnpg fencing on pg-notes pg-notes-1 -n tag14
kubectl cnpg fencing on pg-notes pg-notes-3 -n tag14
kubectl get cluster pg-notes -n tag14 \
  -o jsonpath='{.metadata.annotations.cnpg\.io/fencedInstances}{"\n"}'
time kubectl exec -n tag14 psql-client -- psql -c 'INSERT INTO ha_test DEFAULT VALUES'

Erwartet (gekürzt): Das INSERT hängt.

pg-notes-1 fenced
pg-notes-3 fenced
["pg-notes-1","pg-notes-3"]

In einem zweiten Terminal auf cp1:

export KUBECONFIG=~/pg/tag16/.kc
kubectl get cluster pg-notes -n tag14
kubectl cnpg psql pg-notes -n tag14 -- -Atc "SELECT wait_event, now() - query_start,
  left(query, 40) FROM pg_stat_activity WHERE wait_event = 'SyncRep'"
kubectl exec -n tag14 pg-notes-1 -c postgres -- pg_isready
kubectl cnpg fencing off pg-notes pg-notes-3 -n tag14

Erwartet (gekürzt):

NAME       AGE   INSTANCES   READY   STATUS                     PRIMARY
pg-notes   62m   3           1       Cluster in healthy state   pg-notes-2
SyncRep|00:02:11.207495|INSERT INTO ha_test DEFAULT VALUES
SyncRep|00:02:00.210755|INSERT INTO ha_test DEFAULT VALUES
/controller/run:5432 - no response
command terminated with exit code 2
pg-notes-3 unfenced

Beide Schreiber warten auf SyncRep. Sobald pg-notes-3 zurück ist, kommt im ersten Terminal INSERT 0 1 mit real 2m22s. Der Cluster meldet trotz einer bereiten Instanz „healthy“ – Fencing ist gewollt. Das ist dataDurability: required (Standard): lieber stehen als Daten riskieren. Die Alternative:

kubectl cnpg fencing off pg-notes pg-notes-1 -n tag14
kubectl patch cluster pg-notes -n tag14 --type merge \
  -p '{"spec":{"postgresql":{"synchronous":{"dataDurability":"preferred"}}}}'
kubectl cnpg fencing on pg-notes pg-notes-1 -n tag14
kubectl cnpg fencing on pg-notes pg-notes-3 -n tag14

Etwa 30 s warten – so lange braucht der Operator, um die eingezäunten Replicas aus der Pflichtliste zu nehmen – dann:

time kubectl exec -n tag14 psql-client -- psql -c 'INSERT INTO ha_test DEFAULT VALUES'
kubectl cnpg fencing off pg-notes pg-notes-1 -n tag14
kubectl cnpg fencing off pg-notes pg-notes-3 -n tag14

Erwartet (gekürzt):

INSERT 0 1

real    0m5.165s

Mit preferred nimmt der Operator nicht bereite Replicas aus der Pflichtliste; Schreiben geht weiter, notfalls ohne synchrone Kopie. Zurück auf asynchron – die folgenden Tage rechnen damit:

kubectl patch cluster pg-notes -n tag14 --type merge \
  -p '{"spec":{"postgresql":{"synchronous":null}}}'
kubectl cnpg psql pg-notes -n tag14 -- -Atc \
  'SELECT application_name, sync_state FROM pg_stat_replication'

Erwartet:

cluster.postgresql.cnpg.io/pg-notes patched
pg-notes-1|async
pg-notes-3|async

Fortschritt speichern? Kostenlos registrieren

Drill 6: Rolling Update der Konfiguration

Ein Parameter, der nur ein Reload braucht, ist sofort aktiv:

kubectl patch cluster pg-notes -n tag14 --type merge \
  -p '{"spec":{"postgresql":{"parameters":{"work_mem":"8MB"}}}}'
kubectl cnpg psql pg-notes -n tag14 -- -Atc 'SHOW work_mem'
kubectl get pods -n tag14 | grep pg-notes

Erwartet (gekürzt):

cluster.postgresql.cnpg.io/pg-notes patched
8MB
pg-notes-1    2/2     Running   1 (6m11s ago)   11m
pg-notes-2    2/2     Running   2 (9m36s ago)   43m
pg-notes-3    2/2     Running   0               11m

max_connections braucht einen Neustart. Standard ist primaryUpdateMethod: restart (der Primary startet einfach neu, das sahst du an Tag 15). Mit switchover wechselt der Primary vorher auf eine schon aktualisierte Replica:

kubectl exec -n tag14 psql-client -- psql -qc 'TRUNCATE ha_test'
kubectl patch cluster pg-notes -n tag14 --type merge -p '{"spec":{
  "primaryUpdateMethod":"switchover",
  "postgresql":{"parameters":{"max_connections":"120"}}}}'
while sleep 3; do echo "$(date +%T) $(kubectl get cluster pg-notes -n tag14 \
  -o jsonpath='{.status.currentPrimary} {.status.phase}')"; done | uniq -f1

Erwartet (gekürzt, nach etwa 90 s Strg+C):

cluster.postgresql.cnpg.io/pg-notes patched
05:56:49 pg-notes-2 Cluster in healthy state
05:56:52 pg-notes-2 Applying configuration
05:56:55 pg-notes-2 Waiting for the instances to become active
05:57:18 pg-notes-2 Applying configuration
05:57:21 pg-notes-2 Waiting for the instances to become active
05:57:48 pg-notes-2 Upgrading cluster
05:57:57 pg-notes-3 Upgrading cluster
05:58:14 pg-notes-3 Cluster in healthy state
kubectl get events -n tag14 --field-selector involvedObject.kind=Cluster \
  --sort-by=.lastTimestamp | tail -3
kubectl cnpg psql pg-notes -n tag14 -- -Atc 'SHOW max_connections'

Erwartet (gekürzt, Auswertung: Lücke rund 13,6 s):

...  UpgradingInstance   cluster/pg-notes   Upgrading instance pg-notes-1
...  UpgradingInstance   cluster/pg-notes   Upgrading instance pg-notes-3
...  Switchover          cluster/pg-notes   Initiating switchover to pg-notes-3 to
                                            upgrade pg-notes-2
120

Erst pg-notes-1, dann pg-notes-3, dann Switchover, zuletzt der alte Primary. Ausfallzeit für Schreiber: nur der Switchover.

Fortschritt speichern? Kostenlos registrieren

Drill 7: Node-Drain und PodDisruptionBudget

Zwei PDBs schützen den Cluster: pg-notes (Replicas, max. eine gleichzeitig weg) und pg-notes-primary (0 Störungen). Ein Drain des Primary-Nodes löst deshalb einen Switchover aus. Im geteilten Labor räumst du nur die CNPG-Pods (--pod-selector); ein echter Drain lässt das weg:

kubectl get pods -n tag14 -o wide -L cnpg.io/instanceRole | grep pg-notes
kubectl exec -n tag14 psql-client -- psql -qc 'TRUNCATE ha_test'
kubectl drain worker1 --pod-selector cnpg.io/cluster=pg-notes \
  --delete-emptydir-data --ignore-daemonsets --timeout 90s
kubectl get pods -n tag14 -o wide | grep pg-notes
kubectl get pdb -n tag14

Nimm den Node mit dem Primary.

Erwartet (gekürzt):

pg-notes-1    2/2   Running   ...   worker1   ...   replica
pg-notes-2    2/2   Running   ...   worker2   ...   replica
pg-notes-3    2/2   Running   ...   worker1   ...   primary
node/worker1 cordoned
evicting pod tag14/pg-notes-1
evicting pod tag14/pg-notes-3
error when evicting pods/"pg-notes-3" -n "tag14" (will retry after 5s): Cannot evict
pod as it would violate the pod's disruption budget.
pod/pg-notes-1 evicted
evicting pod tag14/pg-notes-3
pod/pg-notes-3 evicted
node/worker1 drained
pg-notes-1    0/2     Pending   0     ...   <none>    ...
pg-notes-2    2/2     Running   3     ...   worker2   ...
NAME               MIN AVAILABLE   MAX UNAVAILABLE   ALLOWED DISRUPTIONS   AGE
pg-notes           1               N/A               0                     70m
pg-notes-primary   1               N/A               0                     70m

Der PDB hält die Eviction von pg-notes-3 auf, bis der Operator auf pg-notes-2 umgeschaltet hat (Lücke im Labor: 13 s). Das Event dazu: Current primary is running on unschedulable node worker1, switching over from pg-notes-3 .... pg-notes-1 bleibt Pending: local-path-Volumes hängen am Node (didn't match PersistentVolume's node affinity). Der Cluster läuft so lange mit einer Instanz. Wartung fertig:

kubectl uncordon worker1
kubectl get cluster pg-notes -n tag14

Erwartet (nach etwa 30 s):

node/worker1 uncordoned
NAME       AGE   INSTANCES   READY   STATUS                     PRIMARY
pg-notes   71m   3           3       Cluster in healthy state   pg-notes-2

Tipp: Einzelinstanz-Cluster blockieren jeden Drain (kein Switchover möglich). Für Entwicklungs-Cluster gibt es enablePDB: false.

Fortschritt speichern? Kostenlos registrieren

Drill 8: Minor- und Major-Upgrade

Ein Test-Cluster mit PostgreSQL 17.11 in tag16:

cat > ~/pg/tag16/pg-alt.yaml <<'EOF'
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: pg-alt
  namespace: tag16
spec:
  instances: 2
  imageName: ghcr.io/cloudnative-pg/postgresql:17.11-minimal-trixie
  primaryUpdateMethod: switchover
  storage:
    size: 1Gi
  resources:
    requests: {cpu: 50m, memory: 128Mi}
    limits: {memory: 256Mi}
  bootstrap:
    initdb:
      database: app
      owner: app
EOF
kubectl apply -f ~/pg/tag16/pg-alt.yaml
kubectl wait --for=condition=Ready cluster/pg-alt -n tag16 --timeout=180s
kubectl cnpg psql pg-alt -n tag16 -- -d app -c "CREATE TABLE t AS
  SELECT i, md5(i::text) FROM generate_series(1,100000) i" -Atc 'SHOW server_version'

Erwartet (gekürzt):

cluster.postgresql.cnpg.io/pg-alt created
cluster.postgresql.cnpg.io/pg-alt condition met
SELECT 100000
17.11 (Debian 17.11-1.pgdg13+2)

Minor-Update = neues Image:

kubectl patch cluster pg-alt -n tag16 --type merge \
  -p '{"spec":{"imageName":"ghcr.io/cloudnative-pg/postgresql:17.12-minimal-trixie"}}'
kubectl get pods -n tag16 -w -L cnpg.io/instanceRole

Erwartet (gekürzt, nach etwa 2 min Strg+C):

pg-alt-2   1/1     Terminating       0          43s     replica
pg-alt-2   0/1     Init:0/1          0          1s
pg-alt-2   1/1     Running           0          31s     replica
pg-alt-1   1/1     Running           0          2m12s   unhealthy
pg-alt-1   0/1     Running           1 (5s ago) 2m18s   replica
pg-alt-2   1/1     Running           0          41s     primary
pg-alt-1   1/1     Terminating       1 (19s ago) 2m32s  replica
pg-alt-1   0/1     Init:0/1          0          0s
pg-alt-1   1/1     Running           0          30s     replica

Replica neu mit 17.12, Switchover, alter Primary neu – wie Drill 6. Jetzt das Major-Upgrade auf 18 – ebenfalls nur ein neues Image (gleiche Distribution trixie, sonst lehnt CNPG ab):

kubectl patch cluster pg-alt -n tag16 --type merge \
  -p '{"spec":{"imageName":"ghcr.io/cloudnative-pg/postgresql:18.7-minimal-trixie"}}'
kubectl get pods -n tag16 -w

Erwartet (gekürzt, nach etwa 2 min Strg+C):

pg-alt-1                       1/1     Terminating       0          62s
pg-alt-2                       1/1     Terminating       0          119s
pg-alt-2-major-upgrade-d5xhz   0/1     Init:1/2          0          2s
pg-alt-2-major-upgrade-d5xhz   1/1     Running           0          6s
pg-alt-2-major-upgrade-d5xhz   0/1     Completed         0          51s
pg-alt-2                       1/1     Running           0          12s
pg-alt-1-join-8nnjj            0/1     Completed         0          12s
pg-alt-1                       1/1     Running           0          12s

Alle Instanzen stoppen (Ausfall!), ein Job führt pg_upgrade --link auf dem PVC des Primary aus, die Replica wird neu geklont – ihr PVC ist frisch:

kubectl cnpg psql pg-alt -n tag16 -- -d app -Atc 'SHOW server_version' \
  -c 'SELECT count(*) FROM t' -c 'SELECT n_live_tup FROM pg_stat_user_tables'
kubectl get cluster pg-alt -n tag16 -o jsonpath='{.status.pgDataImageInfo}{"\n"}'
kubectl get pvc -n tag16

Erwartet (gekürzt):

18.7 (Debian 18.7-1.pgdg13+2)
100000
0
{"image":"ghcr.io/cloudnative-pg/postgresql:18.7-minimal-trixie","majorVersion":18}
NAME       STATUS   ...   AGE
pg-alt-1   Bound    ...   83s
pg-alt-2   Bound    ...   5m55s

n_live_tup steht auf 0 – die Zähler der kumulativen Statistik beginnen neu. Die Planerstatistiken übernimmt pg_upgrade ab 18; fehlende ergänzt vacuumdb --analyze-in-stages --missing-stats-only (Tag 13). Backups und WAL von vor dem Upgrade taugen nicht für PITR über die Major-Grenze: gleich ein neues Base-Backup ziehen. Schlägt das Upgrade fehl, setzt du das alte Image zurück; die Daten sind unverändert.

kubectl delete cluster pg-alt -n tag16

Fortschritt speichern? Kostenlos registrieren

Übung: Speed-Drills

  1. Zeige die aktuelle Timeline von pg-notes. Zeitziel: 15 s
  2. Zäune pg-notes-3 ein, zeige die Annotation, hebe es wieder auf. Zeitziel: 45 s
  3. Starte nur die Replica pg-notes-1 neu. Zeitziel: 20 s
  4. Mache einen Switchover auf eine Replica deiner Wahl. Zeitziel: 20 s

Lösung

kubectl cnpg status pg-notes -n tag14 | grep Timeline
kubectl cnpg fencing on pg-notes pg-notes-3 -n tag14
kubectl get cluster pg-notes -n tag14 \
  -o jsonpath='{.metadata.annotations.cnpg\.io/fencedInstances}{"\n"}'
kubectl cnpg fencing off pg-notes pg-notes-3 -n tag14
kubectl cnpg restart pg-notes pg-notes-1 -n tag14
kubectl cnpg promote pg-notes pg-notes-3 -n tag14

Erwartet (gekürzt):

Current Write LSN:       0/15035130 (Timeline: 9 - WAL File: 000000090000000000000015)
pg-notes-3 fenced
["pg-notes-3"]
pg-notes-3 unfenced
instance pg-notes-1 restarted
Node pg-notes-3 in cluster pg-notes will be promoted

kubectl cnpg restart löscht bei einer Replica den Pod; beim Primary startet es ihn in-place neu. Ohne Instanz rollt es den ganzen Cluster durch.

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

pg-notes bleibt mit drei asynchronen Instanzen, primaryUpdateMethod: switchover, max_connections=120 und work_mem=8MB für Tag 17 bis 19 stehen.

kubectl get cluster pg-notes -n tag14

Erwartet: 3 Instanzen, 3 bereit, Cluster in healthy state.

kubectl get cluster pg-notes -n tag14 -o jsonpath='{.spec.primaryUpdateMethod}{"\n"}'

Erwartet: switchover.

kubectl cnpg psql pg-notes -n tag14 -- -Atc 'SELECT sync_state FROM pg_stat_replication'

Erwartet: zweimal async.

kubectl get cluster pg-notes -n tag14 \
  -o jsonpath='{.metadata.annotations.cnpg\.io/fencedInstances}{"\n"}'

Erwartet: leer – keine Instanz eingezäunt.

kubectl get nodes

Erwartet: alle Nodes Ready, keiner SchedulingDisabled.

Challenge

Hebe einen PostgreSQL-17-Cluster ohne Ausfall der Quelle auf 18: Lege pg-17 (eine Instanz, 17.12, Datenbank app mit einer Tabelle) an und baue daraus einen neuen Cluster pg-18 mit 18.7 per Import.

Hinweis: bootstrap.initdb.import mit type: microservice und einem Eintrag in externalClusters; als Zugang reicht das Secret pg-17-app.

Lösung

sed -e 's/name: pg-alt$/name: pg-17/' -e 's/17.11-minimal/17.12-minimal/' \
  -e 's/instances: 2/instances: 1/' ~/pg/tag16/pg-alt.yaml > ~/pg/tag16/pg-17.yaml
kubectl apply -f ~/pg/tag16/pg-17.yaml
kubectl wait --for=condition=Ready cluster/pg-17 -n tag16 --timeout=180s
kubectl cnpg psql pg-17 -n tag16 -- -d app -c "CREATE TABLE t AS
  SELECT i, md5(i::text) FROM generate_series(1,100000) i" \
  -c 'ALTER TABLE t OWNER TO app'
cat > ~/pg/tag16/pg-18.yaml <<'EOF'
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: pg-18
  namespace: tag16
spec:
  instances: 1
  imageName: ghcr.io/cloudnative-pg/postgresql:18.7-minimal-trixie
  storage:
    size: 1Gi
  resources:
    requests: {cpu: 50m, memory: 128Mi}
    limits: {memory: 256Mi}
  bootstrap:
    initdb:
      database: app
      owner: app
      import:
        type: microservice
        databases: [app]
        source:
          externalCluster: pg-17
  externalClusters:
  - name: pg-17
    connectionParameters:
      host: pg-17-rw
      user: app
      dbname: app
      sslmode: verify-full
    sslRootCert:
      name: pg-17-ca
      key: ca.crt
    password:
      name: pg-17-app
      key: password
EOF
kubectl apply -f ~/pg/tag16/pg-18.yaml
kubectl wait --for=condition=Ready cluster/pg-18 -n tag16 --timeout=180s
kubectl cnpg psql pg-18 -n tag16 -- -d app -Atc 'SHOW server_version' \
  -c 'SELECT count(*) FROM t' \
  -c "SELECT tableowner FROM pg_tables WHERE tablename = 't'"

Erwartet (gekürzt):

cluster.postgresql.cnpg.io/pg-17 created
SELECT 100000
ALTER TABLE
cluster.postgresql.cnpg.io/pg-18 created
18.7 (Debian 18.7-1.pgdg13+2)
100000
app

Der Import läuft mit pg_dump -Fd und pg_restore --no-acl --no-owner, danach ANALYZE. Die Quelle bleibt lesbar – Schreibzugriffe nach dem Dump fehlen aber im Ziel. Ganz ohne Lücke geht es mit logischer Replikation (Tag 11).

Fortschritt speichern? Kostenlos registrieren

Aufräumen

kubectl delete cluster pg-17 pg-18 -n tag16
kubectl delete pod schreiber -n tag14
kubectl exec -n tag14 psql-client -- psql -c 'DROP TABLE ha_test'
kubectl delete pod psql-client -n tag14
kubectl delete namespace tag16

Erwartet (gekürzt):

cluster.postgresql.cnpg.io "pg-17" deleted from tag16 namespace
cluster.postgresql.cnpg.io "pg-18" deleted from tag16 namespace
pod "schreiber" deleted from tag14 namespace
DROP TABLE
pod "psql-client" deleted from tag14 namespace
namespace "tag16" deleted

Interview-Notiz

  • „Wie lange dauert ein Failover mit CNPG?“ – Pod-Ausfall oder Switchover rund 10–15 s; Node-Ausfall zusätzlich die Erkennungszeit von Kubernetes (rund 50 s), im ungünstigen Fall bis zur Pod-Räumung nach 5 min. Messen, nicht schätzen.
  • „Synchron oder asynchron?“ – Quorum any 1 verliert keinen bestätigten Commit; dataDurability: required hält Schreiber an, wenn keine Replica da ist, preferred schreibt weiter.
  • „Wie machst du ein Major-Upgrade?“ – In-place per neuem Image (pg_upgrade --link, offline, Replicas werden neu geklont) oder blue/green per Import bzw. logischer Replikation; vorher Backup, danach ANALYZE und neues Base-Backup.

Enterprise-Notiz

  • Drei Instanzen auf drei Nodes bzw. Zonen: Standard ist Anti-Affinity nur preferred; mit affinity.podAntiAffinityType: required (und topologyKey Zone) trifft ein Node-Ausfall nie Primary und Replica zugleich.
  • Schnellere Node-Erkennung über kürzere tolerationSeconds bzw. Node-Health-Checks (z. B. Node Problem Detector + Remediation) – mit Bedacht.
  • postgresql.synchronous.failoverQuorum: true verhindert zusammen mit synchroner Replikation Beförderungen, die bestätigte Commits verlieren würden.
  • Updates per GitOps mit primaryUpdateStrategy: supervised für kritische Cluster: Der Operator wartet vor dem Primary auf dein kubectl cnpg promote.
  • Major-Upgrades erst auf einem Klon aus dem Backup proben (Tag 15) und die Dauer von pg_upgrade plus Neu-Klonen der Replicas messen.