Kubernetes: Persist a Database
A database keeps its data on a Persistent Volume Claim. The pod can die and be replaced, and the data stays on the claim for the new pod.
Postgres with its own claim
A StatefulSet gives Postgres a stable name and a claim from its template. The password comes from a Secret. The data folder is the claim, not the pod disk.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:16
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: db-password
key: password
volumeMounts:
- name: db-storage
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: db-storage
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1GiWrite a row to the database
The table lives in the data folder on the claim. That folder is a mounted volume. The pod writes to it like any other folder.
kubectl exec -it postgres-0 -- psql -U postgres -c "CREATE TABLE notes (id serial PRIMARY KEY, text varchar(100));"Delete the pod and watch it return
The StatefulSet brings the pod back with the same name. The new pod mounts the same claim. The test in the closing example shows the data is still there.
kubectl delete pod postgres-0
kubectl get pods -l app=postgresExample
kubectl exec -it postgres-0 -- psql -U postgres -c "CREATE TABLE notes (id serial PRIMARY KEY, text varchar(100)); INSERT INTO notes (text) VALUES ('hello');"
kubectl delete pod postgres-0
kubectl exec -it postgres-0 -- psql -U postgres -c "SELECT * FROM notes;"Key points
- Use a StatefulSet for a database, because it gives the pod a stable name
- Use a PVC for the data folder, so the data outlives the pod
- Use the postgres:16 image, which is the Postgres version used here
- SQL is the language databases use, and CREATE TABLE makes a table.
- Use the standard StorageClass on minikube for the claim
- Use a Secret for the Postgres password, never plain text in the YAML
In this example, the first command creates a table and a row inside Postgres. The second command deletes the pod. The third command reads the table again in the new pod. The row hello is still there. That proves the data survived on the PVC.
Note
deleting the PVC deletes the data, so keep the claim even when the pod is gone
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
A Postgres pod is deleted and a new one starts. Why is the old data still there?