1. Answers
  2. Provisioning dynamic persistent volumes for stateful applications

How do I provision dynamic persistent volumes for stateful applications?

In this guide, we will provision dynamic persistent volumes for stateful applications in a Kubernetes cluster using Pulumi. We will create a StorageClass which defines the provisioner and parameters for dynamic volume provisioning, and a StatefulSet which ensures that each pod gets its own persistent volume.

import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";

// Create a StorageClass for dynamic provisioning
const storageClass = new k8s.storage.v1.StorageClass("dynamic-storage-class", {
    metadata: { name: "dynamic-storage-class" },
    provisioner: "kubernetes.io/aws-ebs", // Change this based on your cloud provider
    parameters: {
        type: "gp2" // Parameter for AWS EBS, change based on your cloud provider
    },
    reclaimPolicy: "Retain",
    volumeBindingMode: "WaitForFirstConsumer"
});

// Create a StatefulSet with a persistent volume claim template
const statefulSet = new k8s.apps.v1.StatefulSet("stateful-app", {
    metadata: { name: "stateful-app" },
    spec: {
        serviceName: "stateful-app",
        replicas: 3,
        selector: {
            matchLabels: { app: "stateful-app" }
        },
        template: {
            metadata: { labels: { app: "stateful-app" } },
            spec: {
                containers: [{
                    name: "app",
                    image: "nginx",
                    volumeMounts: [{
                        name: "data",
                        mountPath: "/usr/share/nginx/html"
                    }]
                }]
            }
        },
        volumeClaimTemplates: [{
            metadata: { name: "data" },
            spec: {
                accessModes: ["ReadWriteOnce"],
                storageClassName: "dynamic-storage-class",
                resources: {
                    requests: {
                        storage: "1Gi"
                    }
                }
            }
        }]
    }
});

Key Points

  • StorageClass: Defines the provisioner and parameters for dynamic volume provisioning.
  • StatefulSet: Manages the deployment and scaling of a set of pods, with guarantees about the ordering and uniqueness of these pods.
  • Persistent Volume Claim Templates: Used in StatefulSets to ensure each pod gets its own persistent volume.

Summary

We created a StorageClass for dynamic provisioning of persistent volumes and a StatefulSet that uses this StorageClass to create persistent volumes for each pod. This setup ensures that each replica of the stateful application has its own dedicated storage.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up