Namespace depths-1lwxvx has a busybox Pod named client. Nothing else.
Headless Service first
The StatefulSet names a Service in spec.serviceName. Create it before the set:
sh
kubectl apply -n depths-1lwxvx -f - <<EOF
apiVersion: v1
kind: Service
metadata:
name: db
spec:
clusterIP: None
selector:
app: db
ports:
- port: 5432
EOFThe StatefulSet
sh
kubectl apply -n depths-1lwxvx -f - <<EOF
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: db
spec:
serviceName: db
replicas: 3
selector:
matchLabels:
app: db
template:
metadata:
labels:
app: db
spec:
containers:
- name: postgres
image: postgres:16
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ReadWriteOnce]
resources:
requests:
storage: 1Gi
EOFWatch it come up one Pod at a time:
sh
kubectl get pods -n depths-1lwxvx -l app=db
kubectl get sts,pvc -n depths-1lwxvxconsole
NAME READY STATUS RESTARTS AGE
db-0 1/1 Running 0 6s
db-1 1/1 Running 0 4s
db-2 1/1 Running 0 2sThree claims appeared: data-db-0, data-db-1, data-db-2, each Bound to its own volume.
Resolve one Pod
sh
kubectl exec client -n depths-1lwxvx -- nslookup db-0.dbThe Name: line prints the full name that resolved. That full name is the answer to one objective.
Scale down, keep the data
sh
kubectl scale sts db --replicas=1 -n depths-1lwxvx
kubectl get pods -n depths-1lwxvx -l app=db
kubectl get pvc -n depths-1lwxvxdb-2 goes first, then db-1. All three claims are still there, still Bound.
Scale back up
sh
kubectl scale sts db --replicas=3 -n depths-1lwxvx
kubectl get pods,pvc -n depths-1lwxvxdb-1 and db-2 return and mount data-db-1 and data-db-2. Same claims, same volumes, same data.