Last updated on February 13, 2025
Setting up PostgreSQL in Kubernetes ensures a scalable and resilient database for your applications. This guide covers deploying PostgreSQL using a StatefulSet and Persistent Volumes.
⚠️ This article is in progress and not verified by author
Prerequisites
- A Kubernetes cluster up and running (e.g., Minikube, k3s, or a managed Kubernetes service like AKS, EKS, or GKE).
kubectl
installed and configured.helm
installed (if using Helm deployment).
Deploy PostgreSQL with StatefulSet
Step 1: Create a Persistent Volume Claim (PVC)
PostgreSQL requires persistent storage to ensure data durability.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: postgres-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
Apply the PVC:
kubectl apply -f postgres-pvc.yaml
Step 2: Deploy PostgreSQL as a StatefulSet
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:latest
ports:
- containerPort: 5432
env:
- name: POSTGRES_DB
value: "mydatabase"
- name: POSTGRES_USER
value: "myuser"
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-secret
key: password
volumeMounts:
- name: postgres-storage
mountPath: /var/lib/postgresql/data
volumes:
- name: postgres-storage
persistentVolumeClaim:
claimName: postgres-pvc
Apply the StatefulSet:
kubectl apply -f postgres-statefulset.yaml
Step 3: Create a PostgreSQL Service
apiVersion: v1
kind: Service
metadata:
name: postgres
spec:
selector:
app: postgres
ports:
- protocol: TCP
port: 5432
targetPort: 5432
clusterIP: None
Apply the Service:
kubectl apply -f postgres-service.yaml
Conclusion
Setting up PostgreSQL in Kubernetes can be done either manually with a StatefulSet or via Helm for easier management. Both methods ensure your database remains persistent and scalable.
This is a test comment