All tools / Kubernetes examples
PostgreSQL on Kubernetes
PostgreSQL as a StatefulSet with a persistent volume, credentials in a Secret, and readiness and liveness checks.
Customize names, versions and passwords →
postgresql.yaml
apiVersion: v1
kind: Secret
metadata:
name: postgres
namespace: default
type: Opaque
stringData:
POSTGRES_USER: "app"
POSTGRES_PASSWORD: "change-me"
POSTGRES_DB: "app"
---
apiVersion: v1
kind: Service
metadata:
name: postgres
namespace: default
spec:
clusterIP: None
selector:
app: postgres
ports:
- name: postgres
port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
namespace: default
spec:
serviceName: postgres
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
securityContext:
fsGroup: 999
containers:
- name: postgres
image: postgres:17
ports:
- name: postgres
containerPort: 5432
envFrom:
- secretRef:
name: postgres
env:
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
readinessProbe:
exec:
command: ["sh", "-c", "pg_isready -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\""]
periodSeconds: 10
livenessProbe:
exec:
command: ["sh", "-c", "pg_isready -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\""]
initialDelaySeconds: 30
periodSeconds: 20
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
memory: 1Gi
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10Gi
Passwords here are placeholders (change-me). The generator creates random ones for you.
How to use it
Commands
kubectl apply -f postgresql.yaml kubectl -n default get pods -w
- Apps in the cluster connect to postgres.default.svc.cluster.local:5432.
- For postgres 18 and later images, mount the volume at /var/lib/postgresql and drop the PGDATA variable.
Prefer Docker Compose? See the PostgreSQL Docker Compose version.