Tag 14: CloudNativePG installieren und erster Cluster
Ziel: Der CloudNativePG-Operator läuft, ein Cluster
pg-notesmit drei PostgreSQL-18-Instanzen dient die Datenbanknotesaus, und du weißt, welche Objekte der Operator anlegt und wie er sich selbst heilt. · Dauer: ca. 90 min · Voraussetzung: Tag 10, Kubernetes-Grundlagen
Briefing
- Ein Operator übernimmt, was du an Tag 0 bis 13 von Hand gemacht hast: initdb, Replikation, Failover, Konfiguration. Du beschreibst nur noch den Soll-Zustand.
- CloudNativePG (CNPG) verwaltet Pods und PVCs selbst – ohne StatefulSet.
- Drei Services:
-rw(Primary),-ro(nur Replicas – in Teil 1 hießen sie Standbys),-r(alle Instanzen). - Ab heute arbeitest du auf
cp1(Kontextost) im Namespacetag14. - Vorher richtest du ein, was Teil 2 im Cluster braucht: Helm, cert-manager sowie Prometheus und Grafana (kube-prometheus-stack).
cp1 (kubectl, kubectl cnpg)
|
cnpg-system: cnpg-controller-manager --- beobachtet ---> Cluster pg-notes
|
tag14: pg-notes-1 (Primary) --WAL--> pg-notes-2, pg-notes-3 (Replicas)
PVC pg-notes-1 PVC pg-notes-2, pg-notes-3
Service pg-notes-rw Service pg-notes-ro / pg-notes-r
Alle Befehle laufen auf cp1 mit einer eigenen
kubeconfig-Kopie:
mkdir -p ~/pg/tag14 && cp ~/.kube/config ~/pg/tag14/.kc
export KUBECONFIG=~/pg/tag14/.kc
kubectl create namespace tag14Vorbereitung: Was Teil 2 im Cluster braucht
Tag 15 und 17 brauchen cert-manager, Tag 17 außerdem Prometheus und
Grafana. Beides kommt per Helm. Hast du die drei schon (etwa aus dem
Cilium-Buch), prüfe nur mit cmctl check api und
helm list -A und setze in Tag 17 deinen Release-Namen,
deinen Namespace und dein Grafana-Passwort ein.
Helm als Binärdatei mit Prüfsumme:
cd /tmp
ARCH=$(dpkg --print-architecture)
H=v4.3.2
curl -fsSLO https://get.helm.sh/helm-$H-linux-${ARCH}.tar.gz
curl -fsSLO https://get.helm.sh/helm-$H-linux-${ARCH}.tar.gz.sha256sum
sha256sum -c helm-$H-linux-${ARCH}.tar.gz.sha256sum
tar xzf helm-$H-linux-${ARCH}.tar.gz
sudo install -m 755 linux-${ARCH}/helm /usr/local/bin/helm
cd -
helm version --shortErwartet (gekürzt):
helm-v4.3.2-linux-amd64.tar.gz: OK
v4.3.2+g8346aaa
cert-manager v1.21.3 aus dem OCI-Chart, dazu die CLI
cmctl (eine Binärdatei pro Architektur):
helm install cert-manager oci://quay.io/jetstack/charts/cert-manager \
--version v1.21.3 -n cert-manager --create-namespace --set crds.enabled=true
kubectl rollout status deploy -n cert-manager
cd /tmp
CM=https://github.com/cert-manager/cmctl/releases/download/v2.6.2
curl -fsSLO $CM/cmctl_linux_${ARCH}
curl -fsSL $CM/checksums.txt | grep " cmctl_linux_${ARCH}$" | sha256sum -c
sudo install -m 0755 cmctl_linux_${ARCH} /usr/local/bin/cmctl
cd -
cmctl check apiErwartet (gekürzt):
Pulled: quay.io/jetstack/charts/cert-manager:v1.21.3
STATUS: deployed
deployment "cert-manager" successfully rolled out
deployment "cert-manager-cainjector" successfully rolled out
deployment "cert-manager-webhook" successfully rolled out
cmctl_linux_amd64: OK
The cert-manager API is ready
kube-prometheus-stack schlank: ohne Alertmanager, Regeln, Node-Exporter und die Control-Plane-Ziele, die bei kubeadm nur auf localhost lauschen:
helm repo add prometheus-community \
https://prometheus-community.github.io/helm-charts
helm repo update prometheus-community
cat > ~/pg/tag14/kps.yaml <<'EOF'
alertmanager:
enabled: false
defaultRules:
create: false
nodeExporter:
enabled: false
kubeProxy:
enabled: false
kubeEtcd:
enabled: false
kubeControllerManager:
enabled: false
kubeScheduler:
enabled: false
grafana:
adminPassword: lab-grafana-123
prometheus:
prometheusSpec:
retention: 12h
podMonitorSelectorNilUsesHelmValues: false
resources:
requests: {cpu: 100m, memory: 256Mi}
limits: {memory: 1Gi}
EOF
helm install kps prometheus-community/kube-prometheus-stack --version 93.4.1 \
-n monitoring --create-namespace -f ~/pg/tag14/kps.yaml
kubectl get pods -n monitoringErwartet (gekürzt; get pods nach etwa 3
min wiederholen, das Grafana-Image hat fast 500 MB):
STATUS: deployed
NAME READY STATUS ...
kps-grafana-6b448f76b6-rlcz4 3/3 Running ...
kps-kube-prometheus-stack-operator-597c48dc56-fxlpr 1/1 Running ...
kps-kube-state-metrics-dc46747f8-tgb67 1/1 Running ...
prometheus-kps-kube-prometheus-stack-prometheus-0 2/2 Running ...
podMonitorSelectorNilUsesHelmValues: false lässt
Prometheus alle PodMonitors im Cluster lesen – sonst nur
die mit dem Label release: kps. ScrapeConfigs
brauchen dieses Label weiterhin (Tag 17). Der Grafana-Sidecar lädt
Dashboards aus ConfigMaps mit dem Label grafana_dashboard=1
aus allen Namespaces. Das Admin-Passwort lab-grafana-123
ist ein Lab-Wert.
Drill 1: Operator und Plugin installieren
Die CNPG-Doku empfiehlt das Release-Manifest. Es enthält Namespace
cnpg-system, CRDs, RBAC, Webhooks und das Deployment des
Operators:
V=1.30.2
kubectl apply --server-side -f https://raw.githubusercontent.com/\
cloudnative-pg/cloudnative-pg/release-1.30/releases/cnpg-$V.yaml
kubectl rollout status deployment -n cnpg-system cnpg-controller-manager
kubectl get deploy -n cnpg-system -o wide
kubectl get crd -o name | grep cnpgErwartet (gekürzt):
namespace/cnpg-system serverside-applied
customresourcedefinition.apiextensions.k8s.io/clusters.postgresql.cnpg.io ...
...
deployment "cnpg-controller-manager" successfully rolled out
NAME READY UP-TO-DATE AVAILABLE ... IMAGES
cnpg-controller-manager 1/1 1 1 ... ghcr.io/cloudnative-...
customresourcedefinition.apiextensions.k8s.io/backups.postgresql.cnpg.io
customresourcedefinition.apiextensions.k8s.io/clusterimagecatalogs.postgresql.cnpg.io
customresourcedefinition.apiextensions.k8s.io/clusters.postgresql.cnpg.io
customresourcedefinition.apiextensions.k8s.io/databaseroles.postgresql.cnpg.io
customresourcedefinition.apiextensions.k8s.io/databases.postgresql.cnpg.io
customresourcedefinition.apiextensions.k8s.io/failoverquorums.postgresql.cnpg.io
customresourcedefinition.apiextensions.k8s.io/imagecatalogs.postgresql.cnpg.io
customresourcedefinition.apiextensions.k8s.io/poolers.postgresql.cnpg.io
customresourcedefinition.apiextensions.k8s.io/publications.postgresql.cnpg.io
customresourcedefinition.apiextensions.k8s.io/scheduledbackups.postgresql.cnpg.io
customresourcedefinition.apiextensions.k8s.io/subscriptions.postgresql.cnpg.io
--server-side ist Pflicht: Die CRDs sind zu groß für die
Annotation, die ein klassisches kubectl apply anlegt. Das
Operator-Image ghcr.io/cloudnative-pg/cloudnative-pg:1.30.2
gibt es für amd64 und arm64.
Tipp: Wer Helm bevorzugt: Chart
cnpg/cloudnative-pgVersion 0.29.2 aushttps://cloudnative-pg.github.io/chartsinstalliert denselben Operator 1.30.2.
Jetzt das Plugin kubectl cnpg. Die Release-Dateien
heißen linux_x86_64 bzw. linux_arm64, deshalb
wird aarch64 umbenannt:
ARCH=$(uname -m | sed s/aarch64/arm64/)
U=https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v$V
cd /tmp
curl -fsSLO $U/kubectl-cnpg_${V}_linux_${ARCH}.tar.gz
curl -fsSLO $U/cnpg-$V-checksums.txt
sha256sum --ignore-missing -c cnpg-$V-checksums.txt
tar -xzf kubectl-cnpg_${V}_linux_${ARCH}.tar.gz kubectl-cnpg
sudo install -m 0755 kubectl-cnpg /usr/local/bin/
cd -
kubectl cnpg versionErwartet:
kubectl-cnpg_1.30.2_linux_x86_64.tar.gz: OK
Build: {Version:1.30.2 Commit:30cca36d3 Date:2026-11-17}
kubectl findet jedes Programm
kubectl-<name> im PATH als Unterbefehl.
Mit Krew geht es auch: kubectl krew install cnpg.
Fortschritt speichern? Kostenlos registrieren
Drill 2: Der erste Cluster
Die Worker haben je 2 vCPU und 4 GB, deshalb bekommt jede Instanz
wenig Speicher. bootstrap.initdb legt die Datenbank
notes mit der Owner-Rolle notes_app an:
cat > ~/pg/tag14/pg-notes.yaml <<'EOF'
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: pg-notes
namespace: tag14
spec:
instances: 3
imageName: ghcr.io/cloudnative-pg/postgresql:18.7-minimal-trixie
storage:
storageClass: local-path
size: 1Gi
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
memory: 512Mi
postgresql:
parameters:
shared_buffers: 64MB
bootstrap:
initdb:
database: notes
owner: notes_app
EOF
kubectl apply -f ~/pg/tag14/pg-notes.yaml
kubectl get pods -n tag14 -wErwartet (gekürzt, nach etwa zwei Minuten mit Strg+C beenden):
cluster.postgresql.cnpg.io/pg-notes created
NAME READY STATUS RESTARTS AGE
pg-notes-1-initdb-jjlhb 0/1 Init:0/1 0 5s
pg-notes-1-initdb-jjlhb 1/1 Running 0 35s
pg-notes-1-initdb-jjlhb 0/1 Completed 0 39s
pg-notes-1 1/1 Running 0 11s
pg-notes-2-join-zzxzs 1/1 Running 0 26s
pg-notes-2-join-zzxzs 0/1 Completed 0 31s
pg-notes-2 1/1 Running 0 11s
pg-notes-3-join-pb75h 0/1 Completed 0 16s
pg-notes-3 1/1 Running 0 11s
Erst ein Job mit initdb für die erste Instanz, dann je
ein join-Job, der per pg_basebackup eine
Replica klont – Tag 10 im Zeitraffer. Das Image bestimmt die Version:
18.7-minimal-trixie ist PostgreSQL 18.7 auf Debian Trixie
ohne Extras (amd64 und arm64). Ohne imageName nimmt CNPG
1.30.2 18.7-system-trixie.
Tipp: Statt den Tag in jeden Cluster zu schreiben, kann ein
ImageCatalog(oder clusterweitClusterImageCatalog) Major-Version auf Image abbilden; der Cluster nennt dann nur nochmajor: 18. Die Challenge probiert das aus.
Fortschritt speichern? Kostenlos registrieren
Drill 3: Was der Operator anlegt
kubectl get cluster -n tag14
kubectl get pods -n tag14 -o wide -L cnpg.io/instanceRole
kubectl get sts,deploy -n tag14
kubectl get pvc,svc -n tag14
kubectl get secrets,pdb -n tag14Erwartet (gekürzt):
NAME AGE INSTANCES READY STATUS PRIMARY
pg-notes 2m30s 3 3 Cluster in healthy state pg-notes-1
NAME READY STATUS ... IP NODE ... INSTANCEROLE
pg-notes-1 1/1 Running ... 10.0.1.139 worker1 ... primary
pg-notes-2 1/1 Running ... 10.0.2.53 worker2 ... replica
pg-notes-3 1/1 Running ... 10.0.1.85 worker1 ... replica
No resources found in tag14 namespace.
NAME STATUS ... CAPACITY ACCESS MODES STORAGECLASS
persistentvolumeclaim/pg-notes-1 Bound ... 1Gi RWO local-path
persistentvolumeclaim/pg-notes-2 Bound ... 1Gi RWO local-path
persistentvolumeclaim/pg-notes-3 Bound ... 1Gi RWO local-path
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/pg-notes-r ClusterIP 10.103.175.65 <none> 5432/TCP 2m39s
service/pg-notes-ro ClusterIP 10.101.253.25 <none> 5432/TCP 2m39s
service/pg-notes-rw ClusterIP 10.105.222.205 <none> 5432/TCP 2m39s
NAME TYPE DATA AGE
secret/pg-notes-app kubernetes.io/basic-auth 11 2m39s
secret/pg-notes-ca Opaque 2 2m39s
secret/pg-notes-replication kubernetes.io/tls 2 2m39s
secret/pg-notes-server kubernetes.io/tls 2 2m39s
NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS AGE
pg-notes 1 N/A 1 2m38s
pg-notes-primary 1 N/A 0 2m38s
Kein StatefulSet: Der Operator legt Pods und PVCs direkt an und
entscheidet selbst, welcher Pod Primary ist (Label
cnpg.io/instanceRole). Die Services wählen über dieses
Label aus. CNPG bringt eine eigene CA mit (pg-notes-ca),
daraus entstehen das Server-Zertifikat und das Client-Zertifikat für
streaming_replica. Der PDB pg-notes-primary
erlaubt 0 Störungen: Ein kubectl drain wartet, bis der
Primary woanders läuft (Tag 16).
Fortschritt speichern? Kostenlos registrieren
Drill 4: Status und psql per Plugin
kubectl cnpg status pg-notes -n tag14Erwartet (gekürzt):
Cluster Summary
Name tag14/pg-notes
System ID: 7709740788768088084
PostgreSQL Image: ghcr.io/cloudnative-pg/postgresql:18.7-minimal-trixie
Primary instance: pg-notes-1
Status: Cluster in healthy state
Instances: 3
Ready instances: 3
Current Write LSN: 0/6032C40 (Timeline: 1 - WAL File: 000000010000000000000006)
Continuous Backup not configured
Streaming Replication status
Replication Slots Enabled
Name Sent LSN ... Replay Lag State Sync State ... Replication Slot
pg-notes-2 0/6032C40 ... 00:00:00 streaming async ... active
pg-notes-3 0/6032C40 ... 00:00:00 streaming async ... active
Instances status
Name Current LSN Replication role Status QoS Manager Version Node
pg-notes-1 0/6032C40 Primary OK Burstable 1.30.2 worker1
pg-notes-2 0/6032C40 Standby (async) OK Burstable 1.30.2 worker2
pg-notes-3 0/6032C40 Standby (async) OK Burstable 1.30.2 worker1
Alles, was du an Tag 10 aus pg_stat_replication
zusammengesucht hast, auf einen Blick. kubectl cnpg psql
startet psql im Primary-Pod als postgres über
den Unix-Socket (peer) – ohne Passwort. Alles nach
-- geht an psql:
kubectl cnpg psql pg-notes -n tag14 -- -c '\l notes' -c '\du'
kubectl cnpg psql pg-notes -n tag14 -- -Atc 'SELECT version()' \
-c 'SHOW shared_buffers' -c 'SELECT pg_is_in_recovery()'
kubectl cnpg psql pg-notes -n tag14 --replica -- -Atc 'SELECT pg_is_in_recovery()'Erwartet (gekürzt):
List of databases
Name | Owner | Encoding | Locale Provider | Collate | Ctype | ...
-------+-----------+----------+-----------------+---------+-------+ ...
notes | notes_app | UTF8 | libc | C | C | ...
List of roles
Role name | Attributes
-----------------------+------------------------------------------------------------
cnpg_metrics_exporter |
notes_app |
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS
streaming_replica | Replication
PostgreSQL 18.7 (Debian 18.7-1.pgdg13+2) on x86_64-pc-linux-gnu, compiled by ...
64MB
f
t
shared_buffers steht auf 64MB wie im Manifest.
Konfiguration ändert man nur noch über den Cluster – der
Operator rollt sie aus (Tag 17).
Achtung:
kubectl cnpg psqlreicht standardmäßig die Standardeingabe an den Pod durch (-i). In einem Heredoc oder Skript schluckt es dabei die folgenden Zeilen. Dortkubectl exec -inehmen oder</dev/nullanhängen.
Fortschritt speichern? Kostenlos registrieren
Drill 5: Die Secrets
pg-notes-app enthält alles, was eine Anwendung
braucht:
kubectl get secret pg-notes-app -n tag14 -o jsonpath='{.data}' | jq -r 'keys[]' \
| paste -sd ' '
kubectl get secret pg-notes-app -n tag14 -o jsonpath='{.data.username}' \
| base64 -d; echo
kubectl get secret pg-notes-app -n tag14 -o jsonpath='{.data.host}' | base64 -d; echoErwartet:
dbname fqdn-jdbc-uri fqdn-uri host jdbc-uri password pgpass port uri user username
notes_app
pg-notes-rw
Der Schlüssel uri hat die Form
postgresql://notes_app:<passwort>@pg-notes-rw.tag14:5432/notes,
pgpass ist eine fertige .pgpass-Zeile. Ein
Secret pg-notes-superuser fehlt:
enableSuperuserAccess steht standardmäßig auf
false. Zum Ausprobieren an und wieder aus:
kubectl patch cluster pg-notes -n tag14 --type merge \
-p '{"spec":{"enableSuperuserAccess":true}}'
kubectl get secrets -n tag14
kubectl get secret pg-notes-superuser -n tag14 -o jsonpath='{.data.username}' \
| base64 -d; echo
kubectl patch cluster pg-notes -n tag14 --type merge \
-p '{"spec":{"enableSuperuserAccess":false}}'
kubectl get secrets -n tag14 -o nameErwartet (gekürzt):
cluster.postgresql.cnpg.io/pg-notes patched
NAME TYPE DATA AGE
pg-notes-app kubernetes.io/basic-auth 11 3m33s
...
pg-notes-superuser kubernetes.io/basic-auth 11 8s
postgres
cluster.postgresql.cnpg.io/pg-notes patched
secret/pg-notes-app
secret/pg-notes-ca
secret/pg-notes-replication
secret/pg-notes-server
Beim Abschalten löscht der Operator das Secret und setzt das Passwort
von postgres auf NULL – Anmeldung per Passwort
ist damit unmöglich. Die Pods starten dafür nicht neu. Admin-Arbeit geht
weiter über kubectl cnpg psql – das braucht nur RBAC-Rechte
für pods/exec.
Fortschritt speichern? Kostenlos registrieren
Drill 6: Verbindung aus einem Pod
Ein Client-Pod bekommt die Verbindungsdaten aus dem Secret als
PG*-Variablen, die psql von selbst liest. Das
PostgreSQL-Image bringt psql mit:
cat > ~/pg/tag14/psql-client.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: psql-client
namespace: tag14
spec:
containers:
- name: psql
image: ghcr.io/cloudnative-pg/postgresql:18.7-minimal-trixie
command: ["sleep", "infinity"]
env:
- 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/tag14/psql-client.yaml
kubectl wait --for=condition=Ready pod/psql-client -n tag14
kubectl exec -n tag14 psql-client -- psql -c '\conninfo' \
| grep -E 'Database|Client User|Host |Password|SSL (Conn|Proto)|Hot'Erwartet:
pod/psql-client created
pod/psql-client condition met
Database | notes
Client User | notes_app
Host | pg-notes-rw
Password Used | true
SSL Connection | true
SSL Protocol | TLSv1.3
Hot Standby | off
TLS ist ohne weiteres Zutun an. notes_app ist Owner der
Datenbank und darf daher im Schema public Tabellen anlegen
– anders als an Tag 0. Dieselbe Tabelle wie auf pg1:
kubectl exec -i -n tag14 psql-client -- psql <<'EOF'
CREATE TABLE notes (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO notes (text) VALUES ('Tag 14: erster CNPG-Cluster');
INSERT INTO notes (text, created_at)
SELECT 'Testnotiz ' || i, now() - i * interval '1 minute'
FROM generate_series(1, 1000) AS i;
EOFErwartet:
CREATE TABLE
INSERT 0 1
INSERT 0 1000
Jetzt lesen und schreiben über den Read-only-Service:
kubectl exec -n tag14 psql-client -- psql -h pg-notes-ro \
-Atc 'SELECT count(*), pg_is_in_recovery(), inet_server_addr() FROM notes'
kubectl exec -n tag14 psql-client -- psql -h pg-notes-ro \
-c 'INSERT INTO notes (text) VALUES (1)'
kubectl get endpointslices -n tag14 \
-o custom-columns=NAME:.metadata.name,ADDR:.endpoints[*].addresses[0]Erwartet:
1001|t|10.0.1.85
ERROR: cannot execute INSERT in a read-only transaction
command terminated with exit code 1
NAME ADDR
pg-notes-r-tvs8n 10.0.1.139,10.0.2.53,10.0.1.85
pg-notes-ro-ktk62 10.0.2.53,10.0.1.85
pg-notes-rw-2rxv7 10.0.1.139
Die 1001 Zeilen sind per Streaming-Replikation schon auf der Replica
10.0.1.85 (pg-notes-3). -ro
verteilt Leselast auf die Replicas, -r schließt den Primary
ein. Schreiben geht nur über -rw.
Fortschritt speichern? Kostenlos registrieren
Drill 7: Port-Forward und TLS von außen
Für einen kurzen Blick von außen reicht
kubectl port-forward. Er lauscht auf cp1 an
allen Adressen, damit pg2 als Client dienen kann. Vorher
das CA-Zertifikat holen:
kubectl get secret pg-notes-ca -n tag14 -o jsonpath='{.data.ca\.crt}' \
| base64 -d > ~/pg/tag14/pg-notes-ca.crt
openssl x509 -in ~/pg/tag14/pg-notes-ca.crt -noout -subject -enddate
kubectl get secret pg-notes-app -n tag14 -o jsonpath='{.data.password}' \
| base64 -d; echo
kubectl port-forward -n tag14 --address 0.0.0.0 svc/pg-notes-rw 15432:5432 &Erwartet (gekürzt):
subject=OU = tag14, CN = pg-notes
notAfter=Feb 17 04:46:12 2027 GMT
<zufälliges Passwort>
Forwarding from 0.0.0.0:15432 -> 5432
Zwischen cp1 und pg2 gibt es keinen
SSH-Zugang. Das CA-Zertifikat (nur ca.crt) wandert deshalb
wie in Tag 3 über deinen Rechner. Von deinem Rechner aus:
ssh [email protected] cat pg/tag14/pg-notes-ca.crt \
| ssh [email protected] 'cat > pg-notes-ca.crt'Auf pg2 (Passwort von oben eingeben):
psql "host=172.16.0.126 port=15432 dbname=notes user=notes_app \
sslmode=verify-ca sslrootcert=pg-notes-ca.crt" \
-c 'SELECT count(*) FROM notes' -c '\conninfo' \
| grep -E 'count|^ +[0-9]|Host |Port|SSL (Conn|Proto)'Erwartet:
Password for user notes_app:
count
1001
Host | 172.16.0.126
Server Port | 15432
SSL Connection | true
SSL Protocol | TLSv1.3
verify-ca prüft, dass das Zertifikat von der CNPG-CA
stammt. verify-full schlägt hier fehl, weil das Zertifikat
nur die Service-Namen kennt:
psql: error: connection to server at "172.16.0.126", port 15432 failed: server
certificate for "pg-notes-rw" (and 12 other names) does not match host name
"172.16.0.126"
Achtung: Ohne
sslrootcertlandetpsqlbeisslmode=preferstill auf einer unverschlüsselten Verbindung, wenn~/.postgresql/root.crt(Tag 3) eine andere CA enthält: Die TLS-Prüfung scheitert,psqlprobiert es ohne TLS, und die CNPG-Regelhost all all all scram-sha-256lässt das zu.
Im Labor endete der Port-Forward nach der ersten TLS-Sitzung mit
error: lost connection to pod (kubectl 1.37.2). Für die
nächste Sitzung neu starten. Für Anwendungen ist er ohnehin nichts – die
verbinden sich im Cluster über die Services. Beenden auf
cp1:
kill %1Fortschritt speichern? Kostenlos registrieren
Drill 8: Selbstheilung und Primary-Wechsel
Zuerst stirbt eine Replica. Achte auf die UID des PVC:
kubectl get pvc pg-notes-3 -n tag14 -o jsonpath='{.metadata.uid}{"\n"}'
kubectl delete pod pg-notes-3 -n tag14
kubectl get pods -n tag14 -wErwartet (gekürzt, nach etwa 20 s Strg+C):
23a33de6-acb1-41cd-835d-250d64809eca
pod "pg-notes-3" deleted from tag14 namespace
NAME READY STATUS RESTARTS AGE
pg-notes-1 1/1 Running 0 6m17s
pg-notes-2 1/1 Running 0 11m
pg-notes-3 0/1 Pending 0 0s
pg-notes-3 0/1 Init:0/1 0 0s
pg-notes-3 0/1 PodInitializing 0 3s
pg-notes-3 0/1 Running 0 4s
pg-notes-3 1/1 Running 0 12s
kubectl get pvc pg-notes-3 -n tag14 -o jsonpath='{.metadata.uid}{"\n"}'
kubectl exec -n tag14 psql-client -- psql -h pg-notes-ro \
-Atc 'SELECT count(*) FROM notes'Erwartet:
23a33de6-acb1-41cd-835d-250d64809eca
1001
Gleicher Name, gleiches PVC: Die Instanz startet auf ihren alten Daten und holt nur das fehlende WAL nach. Jetzt der Primary:
kubectl delete pod pg-notes-1 -n tag14
kubectl get cluster pg-notes -n tag14 \
-o jsonpath='{.status.currentPrimary} {.status.phase}{"\n"}'Den zweiten Befehl ein paar Mal wiederholen.
Erwartet (gekürzt):
pod "pg-notes-1" deleted from tag14 namespace
pg-notes-1 Failing over
pg-notes-2 Waiting for the instances to become active
pg-notes-2 Cluster in healthy state
kubectl get pods -n tag14 -L cnpg.io/instanceRole
kubectl exec -n tag14 psql-client -- psql \
-Atc 'SELECT pg_is_in_recovery(), inet_server_addr(), count(*) FROM notes'
kubectl cnpg status pg-notes -n tag14 | grep -E 'Primary instance|Timeline'Erwartet (gekürzt):
NAME READY STATUS RESTARTS AGE INSTANCEROLE
pg-notes-1 1/1 Running 0 61s replica
pg-notes-2 1/1 Running 0 6m23s primary
pg-notes-3 1/1 Running 0 99s replica
psql-client 1/1 Running 0 3m57s
f|10.0.2.53|1001
Primary instance: pg-notes-2
Current Write LSN: 0/700B568 (Timeline: 2 - WAL File: 000000020000000000000007)
In rund 15 Sekunden war pg-notes-2 befördert,
-rw zeigt auf ihn, und der alte Primary kam als Replica
zurück – das, wofür du an Tag 10 pg_promote und
pg_rewind gebraucht hast. Die Timeline springt auf 2.
Geplante Switchover, Fencing und Updates macht Tag 16.
Fortschritt speichern? Kostenlos registrieren
Übung: Speed-Drills
- Zeige, welcher Pod gerade Primary ist. Zeitziel: 10 s
- Zähle die Zeilen in
notesauf einer Replica, ohne den Client-Pod. Zeitziel: 30 s - Zeige vom Primary aus, welche Replicas streamen. Zeitziel: 45 s
- Zeige, welche PodDisruptionBudgets den Cluster schützen. Zeitziel: 10 s
Lösung
kubectl get cluster -n tag14
kubectl cnpg psql pg-notes -n tag14 --replica -- -d notes \
-Atc 'SELECT count(*), pg_is_in_recovery() FROM notes'
kubectl cnpg psql pg-notes -n tag14 -- -c 'SELECT application_name, client_addr,
state, sync_state FROM pg_stat_replication'
kubectl get pdb -n tag14Erwartet (gekürzt):
NAME AGE INSTANCES READY STATUS PRIMARY
pg-notes ... 3 3 Cluster in healthy state pg-notes-2
1001|t
application_name | client_addr | state | sync_state
------------------+-------------+-----------+------------
pg-notes-3 | 10.0.1.115 | streaming | async
pg-notes-1 | 10.0.1.197 | streaming | async
(2 rows)
NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS AGE
pg-notes 1 N/A 1 ...
pg-notes-primary 1 N/A 0 ...
kubectl cnpg psql verbindet sich ohne -d
mit der Datenbank postgres.
Fortschritt speichern? Kostenlos registrieren
Kontrollpunkt
Operator und Cluster pg-notes, cert-manager und
kube-prometheus-stack bleiben für Tag 15 bis 18 stehen.
cmctl check apiErwartet:
The cert-manager API is ready
helm list -AErwartet: cert-manager (Chart
cert-manager-v1.21.3) und kps (Chart
kube-prometheus-stack-93.4.1), beide
deployed.
kubectl get pods -n monitoringErwartet: Grafana 3/3, Operator und
kube-state-metrics 1/1, Prometheus 2/2, alle
Running.
kubectl get deploy -n cnpg-system cnpg-controller-managerErwartet: 1/1 bereit, Image
ghcr.io/cloudnative-pg/cloudnative-pg:1.30.2.
kubectl cnpg versionErwartet:
Build: {Version:1.30.2 ...}
kubectl get cluster pg-notes -n tag14Erwartet: 3 Instanzen, 3
bereit, Cluster in healthy state.
kubectl get pods -n tag14 -l cnpg.io/instanceRole=primaryErwartet: genau ein Pod (nach Drill 8
pg-notes-2).
kubectl cnpg psql pg-notes -n tag14 -- -d notes -Atc 'SELECT count(*) FROM notes'Erwartet: 1001 (oder mehr, falls du
zusätzlich geschrieben hast).
kubectl get svc -n tag14 -o nameErwartet: service/pg-notes-r,
service/pg-notes-ro, service/pg-notes-rw.
kubectl get secret -n tag14 pg-notes-superuserErwartet: Error from server (NotFound)
– Superuser-Zugang ist aus.
Challenge
Lege im Namespace tag14 einen ImageCatalog
pg-minimal mit den Images für die Major-Versionen 17 und 18
an und starte daraus einen Cluster pg-mini mit einer
Instanz und PostgreSQL 18. Zeige die Server-Version, dann lösche beides
wieder.
Hinweis: Der Cluster nennt statt
imageName ein imageCatalogRef mit
apiGroup, kind, name und
major; welche 17er-Tags es gibt, zeigt die Registry
(ghcr.io/cloudnative-pg/postgresql).
Lösung
cat > ~/pg/tag14/catalog.yaml <<'EOF'
apiVersion: postgresql.cnpg.io/v1
kind: ImageCatalog
metadata:
name: pg-minimal
namespace: tag14
spec:
images:
- major: 17
image: ghcr.io/cloudnative-pg/postgresql:17.12-minimal-trixie
- major: 18
image: ghcr.io/cloudnative-pg/postgresql:18.7-minimal-trixie
---
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: pg-mini
namespace: tag14
spec:
instances: 1
imageCatalogRef:
apiGroup: postgresql.cnpg.io
kind: ImageCatalog
name: pg-minimal
major: 18
storage:
size: 512Mi
resources:
requests: {cpu: 50m, memory: 128Mi}
limits: {memory: 256Mi}
EOF
kubectl apply -f ~/pg/tag14/catalog.yaml
kubectl get cluster -n tag14
kubectl cnpg psql pg-mini -n tag14 -- -Atc 'SHOW server_version'
kubectl get cluster pg-mini -n tag14 -o jsonpath='{.status.image}{"\n"}'
kubectl delete -f ~/pg/tag14/catalog.yamlErwartet (gekürzt, nach etwa einer Minute):
imagecatalog.postgresql.cnpg.io/pg-minimal created
cluster.postgresql.cnpg.io/pg-mini created
NAME AGE INSTANCES READY STATUS PRIMARY
pg-mini 75s 1 1 Cluster in healthy state pg-mini-1
pg-notes 9m28s 3 3 Cluster in healthy state pg-notes-2
18.7 (Debian 18.7-1.pgdg13+2)
ghcr.io/cloudnative-pg/postgresql:18.7-minimal-trixie
imagecatalog.postgresql.cnpg.io "pg-minimal" deleted from tag14 namespace
cluster.postgresql.cnpg.io "pg-mini" deleted from tag14 namespace
Ohne storageClass nimmt CNPG die Default-Klasse
(local-path). Mit dem Cluster verschwinden auch Pods und
PVC. Ein Minor-Update wird so zu einer Zeile im Katalog – alle Cluster,
die darauf zeigen, rollen nach. Der 17er-Eintrag ist die Vorlage für das
Major-Upgrade an Tag 16.
Fortschritt speichern? Kostenlos registrieren
Aufräumen
Nur der Client-Pod geht. Operator, pg-notes und
~/pg/tag14/*.yaml bleiben:
kubectl delete pod psql-client -n tag14
kubectl get pods -n tag14Erwartet (gekürzt):
pod "psql-client" deleted from tag14 namespace
NAME READY STATUS RESTARTS AGE
pg-notes-1 1/1 Running 0 ...
pg-notes-2 1/1 Running 0 ...
pg-notes-3 1/1 Running 0 ...
Interview-Notiz
- „Warum ein Operator statt StatefulSet?“ – Ein StatefulSet kennt
keine Rollen. CNPG weiß, wer Primary ist, klont Replicas, befördert bei
Ausfall und biegt den
-rw-Service um; dafür verwaltet er Pods und PVCs selbst. - „Wie kommt die Anwendung an die Zugangsdaten?“ – Aus dem Secret
<cluster>-app(Benutzer, Passwort,uri,pgpass), persecretKeyRefoder als Datei gemountet; Ziel ist der Service<cluster>-rw, Lesezugriffe gern über-ro. - „Was passiert, wenn der Primary-Pod stirbt?“ – Der Operator befördert die Replica mit dem neuesten LSN, die Timeline steigt, der alte Primary kommt als Replica zurück. Wer in der Lücke schreibt, bekommt kurz Verbindungsfehler.
Enterprise-Notiz
- Operator per GitOps (Argo CD, Flux) mit fester Version, Upgrades geplant; die Release-Notes nennen Änderungen am Default-Image und an den CRDs.
- Images aus einem internen Spiegel, gepinnt per Digest oder über
einen
ClusterImageCatalog, den ein Plattform-Team pflegt. - Speicher: lokale NVMe (local-path, TopoLVM, OpenEBS LVM) mit
Anti-Affinity über Nodes und Zonen statt Netzwerk-Storage; WAL auf
eigenem Volume (
walStorage). - Requests = Limits für Speicher (QoS
Guaranteed),shared_bufferspassend zum Limit; hierBurstablemit 256/512 Mi ist ein Laborwert. - TLS mit Zertifikaten von cert-manager oder der Firmen-CA, Clients
mit
verify-fullüber die Service-Namen; Superuser-Zugang bleibt aus.