Deploy Postgresql in Kubernetes with backup

Deploying PostgreSQL as a standard Kubernetes Deployment does not guarantee stable pod identity or reliable storage reattachment after restarts. This template deploys PostgreSQL 15 as a StatefulSet with a PersistentVolumeClaim, a headless Service for stable DNS, externalized credentials, a readiness probe, and a scheduled backup CronJob, giving you a production-grade PostgreSQL deployment on Kubernetes that maintains data integrity across pod restarts.
| Component | Type | Port | Role |
|---|---|---|---|
| PostgreSQL 15 | StatefulSet | 5432 | Primary database with stable pod identity and persistent storage |
| PersistentVolumeClaim | PersistentVolumeClaim | - | ReadWriteOnce data volume that reattaches after pod restarts |
| Headless Service | Service | - | Stable DNS resolution for direct pod addressing |
| ConfigMap | ConfigMap | - | Database name and user configuration |
| Secret | Secret | - | Password injected as environment variable at runtime |
| Backup CronJob | CronJob | - | Scheduled database backups |
PostgreSQL 15 runs as a StatefulSet so each pod gets a stable name (postgres-0) and DNS address via the headless Service (postgres-0.postgres-headless). A PVC with ReadWriteOnce access mode binds to the pod and reattaches automatically after restarts. The ConfigMap holds the database name and user, while a Kubernetes Secret injects the password at runtime. A readiness probe using pg_isready gates traffic until the database is ready to accept connections. A CronJob handles scheduled backups.
kubectl get pods,pvc -n <namespace>.kubectl exec -it postgres-0 -n <namespace> -- psql -U <username> -d <dbname>.\l to list databases and verify your configured database exists.SELECT version(); to confirm PostgreSQL 15 is running.This template configures a PostgreSQL 15 StatefulSet on Kubernetes with persistent storage, stable DNS via a headless Service, externalized credentials, and scheduled backups.