How do I run databases with persistent storage on Kubernetes?
In this guide, we will set up a MySQL database on a Kubernetes cluster with persistent storage using Pulumi. This ensures that your database data is retained even if the pod is terminated or rescheduled.
We will use the following Kubernetes resources:
PersistentVolume
(PV): Provides the storage resource.PersistentVolumeClaim
(PVC): Requests storage resources.StatefulSet
: Manages the deployment and scaling of a set of Pods with persistent storage.
Below is the complete Pulumi program in TypeScript:
import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";
// Define the PersistentVolume (PV)
const pv = new k8s.core.v1.PersistentVolume("mysql-pv", {
metadata: { name: "mysql-pv" },
spec: {
capacity: { storage: "10Gi" },
accessModes: ["ReadWriteOnce"],
persistentVolumeReclaimPolicy: "Retain",
hostPath: { path: "/mnt/data" },
},
});
// Define the PersistentVolumeClaim (PVC)
const pvc = new k8s.core.v1.PersistentVolumeClaim("mysql-pvc", {
metadata: { name: "mysql-pvc" },
spec: {
accessModes: ["ReadWriteOnce"],
resources: { requests: { storage: "10Gi" } },
},
});
// Define the StatefulSet for MySQL
const appLabels = { app: "mysql" };
const statefulSet = new k8s.apps.v1.StatefulSet("mysql", {
metadata: { name: "mysql" },
spec: {
selector: { matchLabels: appLabels },
serviceName: "mysql",
replicas: 1,
template: {
metadata: { labels: appLabels },
spec: {
containers: [{
name: "mysql",
image: "mysql:5.7",
ports: [{ containerPort: 3306, name: "mysql" }],
volumeMounts: [{
name: "mysql-storage",
mountPath: "/var/lib/mysql",
}],
env: [
{ name: "MYSQL_ROOT_PASSWORD", value: "password" },
],
}],
},
},
volumeClaimTemplates: [{
metadata: { name: "mysql-storage" },
spec: {
accessModes: ["ReadWriteOnce"],
resources: { requests: { storage: "10Gi" } },
},
}],
},
});
// Export the StatefulSet name
export const statefulSetName = statefulSet.metadata.name;
Key Points
- PersistentVolume (PV): Provides the physical storage for the database.
- PersistentVolumeClaim (PVC): Requests the storage resources from the PV.
- StatefulSet: Ensures the database pod has persistent storage and manages its state.
Summary
In this example, we created a MySQL database on Kubernetes with persistent storage using Pulumi. We defined a PersistentVolume
, a PersistentVolumeClaim
, and a StatefulSet
to ensure data persistence and manage the database pod. This setup ensures that your database data is retained even if the pod is terminated or rescheduled.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.