Deploy MySQL on Kubernetes with Backup: StatefulSet Template

Running MySQL on Kubernetes as a standard Deployment does not guarantee stable pod identity or ordered lifecycle management, which can lead to data inconsistency and storage reattachment failures. This template deploys MySQL 8.0 as a StatefulSet with VolumeClaimTemplates, a headless Service for stable DNS, a ClusterIP Service for load-balanced connections, a non-root security context, externalized credentials, and a scheduled backup CronJob.
| Component | Type | Port | Role |
|---|---|---|---|
| MySQL 8.0 | StatefulSet | 3306 | Primary database with stable pod identity and ordered lifecycle |
| PVC (via VolumeClaimTemplates) | PersistentVolumeClaim | - | Automatically provisioned persistent storage per pod |
| Headless Service | Service | - | Stable DNS for direct pod addressing (mysql-0.mysql-headless) |
| ClusterIP Service | Service | 3306 | Load-balanced access for standard database connections |
| ConfigMap | ConfigMap | - | Non-sensitive database name configuration |
| Secret | Secret | - | MySQL credentials injected at runtime |
| Backup CronJob | CronJob | - | Scheduled database backups |
MySQL 8.0 runs as a StatefulSet with VolumeClaimTemplates that automatically provision a PVC per pod. A headless Service provides stable DNS addresses (mysql-0.mysql-headless.default.svc.cluster.local) for clients that require a direct connection to a specific pod. A standard ClusterIP Service handles load-balanced traffic for general database clients. The ConfigMap stores the database name and the Secret injects credentials at runtime. A SecurityContext enforces non-root execution at UID 1001. A CronJob handles scheduled backups.
kubectl get pods,pvc -n <namespace>.kubectl exec -it mysql-0 -n <namespace> -- mysql -u <username> -p.SHOW DATABASES; to confirm your configured database is listed.SELECT VERSION(); to verify MySQL 8.0 is running.This template configures a MySQL 8.0 StatefulSet on Kubernetes with automatic persistent storage, dual-service networking, a non-root security context, externalized credentials, and scheduled backups.