Understanding and Using StatefulSets and Headless Services
30%
StatefulSet & Headless Service for PostgreSQL: Putting It All Together
In the previous examples, we deployed a PostgreSQL database using a Deployment. In this example, we will deploy the same using a StatefulSet. Our goal is not to provide a complete production-ready PostgreSQL deployment but rather to see in practice how to create a StatefulSet and a Headless Service.
Let's delete some resources that we created in the previous examples:
cd $HOME/stateful-flask
kubectl delete -f kubernetes/postgres-deployment.yaml
kubectl delete -f kubernetes/postgres-service.yaml
kubectl delete -f kubernetes/postgres-pvc-pv.yaml
Now, create the following StatefulSet:
cat < kubernetes/postgres-statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
namespace: postgres
spec:
replicas: 1
selector:
matchLabels:
app: postgres
serviceName: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:18
ports:
- containerPort: 5432
envFrom:
- configMapRef:
name: postgres-config
volumeMounts:
- name: postgredb-volume
mountPath: /var/lib/postgresql
subPath: data
env:
- name: PGDATA
value: /var/lib/postgresql/data/
volumeClaimTemplates:
- metadata:
name: postgredb-volume
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: "do-block-storage"
resources:
requests:Cloud-Native Microservices With Kubernetes - 2nd Edition
A Comprehensive Guide to Building, Scaling, Deploying, Observing, and Managing Highly-Available Microservices in KubernetesEnroll now to unlock all content and receive all future updates for free.
