Database with StatefulSet
- Docker & Kubernetes course
- Advanced
- Lesson 62/70
- 4 min
Write the database as a StatefulSet.
The database with a StatefulSet
The database moves to a single-replica StatefulSet: it gets a stable name (db-0), a persistent disk (data-db-0) and a headless service. The template takes the disk size from the values:
# templates/db-statefulset.yaml (summary)
spec:
serviceName: db
replicas: 1
template:
spec:
containers:
- name: postgres
image: postgres:16
envFrom:
- secretRef: {name: db-gizli}
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata: {name: data}
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: {{ .Values.db.storage }}Testing the database
After installing, it's tested that the database is ready, the disk is attached and the stable name resolves:
kubectl rollout status sts/db -n magaza
kubectl get pvc -n magaza
kubectl exec -n magaza db-0 -- pg_isready -U postgres
/var/run/postgresql:5432 - accepting connections
kubectl exec -n magaza deploy/api -- getent hosts db-0.dbPractice Verify the database
Write three commands: wait for sts/db's rollout to finish in magaza; list the PVCs in magaza; run pg_isready -U postgres in the db-0 pod in magaza.
Starter code
# buraya yazSample solution
kubectl rollout status sts/db -n magaza
kubectl get pvc -n magaza
kubectl exec -n magaza db-0 -- pg_isready -U postgresExpected output
partitioned roll out complete: 1 new pods have been updated... NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS data-db-0 Bound pvc-5e6f… 20Gi RWO hizli-ssd /var/run/postgresql:5432 - accepting connections
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In this setup, what happens to the database data if helm uninstall magaza is run?
- It moves to another namespace
- The PVC (data-db-0) remains; the data is kept Correct answer
- It's deleted immediately
- It moves to a backup
Explanation: PVCs created from volumeClaimTemplates aren't part of the Helm release.
2 Take the disk size from the values.
storage: {{ .____.db.storage }}
storage: {{ .Values.db.storage }}
Explanation: .Values is the values from the values files.
3 Match.
| Term | Meaning |
|---|---|
db-0 |
Stable pod name |
data-db-0 |
Persistent disk |
pg_isready |
Is the database ready |
db-0.db |
Pod DNS name |