Storage: Managing Stateful Applications
9 min read
🚢 Storage: Managing Stateful Applications
Welcome, intrepid Kubernetes navigator! So far, we've treated our application pods like mayflies—here one moment, gone the next, with no memory of what came before. This is fine for stateless applications that don't need to remember anything. But what about our precious databases, the keepers of our secrets and high scores? They need a place to store their data that doesn't disappear when a pod decides to take a permanent vacation.
This guide will walk you through the essential concepts of Kubernetes storage, ensuring your stateful applications have a reliable place to call home.
1. Ephemeral vs. Persistent Storage in Containers ephemeral storage vs persistent storage in containers kubernetes
The Problem: The Forgetful Container 😫
By default, containers are designed to be stateless. Any data written to a container's filesystem is ephemeral, meaning it's tied to the lifecycle of the pod. If the pod crashes, is deleted, or rescheduled to another node, all its data is lost forever. Imagine a database that forgets everything every time it restarts – not exactly ideal for keeping track of user accounts or critical information!
The Solution: A Place to Remember 🧠
To solve this, Kubernetes provides a way to give our applications a memory that persists beyond the life of a single pod. This is where persistent storage comes in. It allows data to exist independently of any pod, ensuring that even if a pod goes down, the data remains safe and sound, ready for the next pod to pick up where the last one left off.
Here's a quick rundown of the two main storage types:
Ephemeral Volumes:
- Definition: Temporary storage that is tied to the lifecycle of a pod.
- Use Cases: Good for temporary data like caches or logs that you don't need to keep around. Common types include
emptyDir,configMap, andsecret. - The Catch: When the pod is deleted, the ephemeral volume and its data are also deleted.
Persistent Volumes:
- Definition: Storage that exists independently of a pod's lifecycle, allowing data to be preserved even after a pod is deleted or rescheduled.
- Use Cases: Essential for stateful applications like databases (MySQL, PostgreSQL), message queues, and any application that needs to maintain state.
- The Win: Provides the data durability required for real-world applications.
2. Persistent Volumes (PV) and Persistent Volume Claims (PVC)
The Problem: Developers Shouldn't Need a Degree in Storage Administration 🎓
So, we need persistent storage. But how do we connect our pods to it? We could have developers directly reference specific storage devices in their pod configurations. However, this would tightly couple the application to the underlying infrastructure. What if the storage details change? The developer would have to update their application's configuration. This isn't very portable or scalable.
The Solution: A Two-Step Handshake 🤝
Kubernetes solves this with a clever abstraction using two key API resources: PersistentVolumes (PVs) and PersistentVolumeClaims (PVCs). Think of it as a separation of duties.
PersistentVolume (PV): A piece of storage in the cluster that has been provisioned by an administrator. It's a resource in the cluster, just like a CPU or memory. PVs abstract away the details of the underlying storage implementation, whether it's a cloud provider's disk, an on-premise SAN, or an NFS share.
PersistentVolumeClaim (PVC): A request for storage by a user. It's like a pod requesting CPU and memory. A PVC specifies the desired size and access mode for the storage.
How they work together:
- An administrator provisions a
PersistentVolumewith a certain size and access mode. - A developer creates a
PersistentVolumeClaimrequesting a certain amount of storage. - Kubernetes then plays matchmaker and binds the
PVCto a suitablePV. - Finally, the developer can mount this
PVCas a volume in their pod's specification, giving the pod access to the persistent storage.
This decoupling allows developers to request storage without needing to know the nitty-gritty details of the underlying storage infrastructure.
Access Modes:
When you define a PV or request storage with a PVC, you need to specify an access mode. This determines how the volume can be mounted. The most common ones are:
ReadWriteOnce(RWO): The volume can be mounted as read-write by a single node.ReadOnlyMany(ROX): The volume can be mounted as read-only by many nodes.ReadWriteMany(RWX): The volume can be mounted as read-write by many nodes.
Example Time! 💻
Let's see what a simple PV and PVC look like in YAML.
A PersistentVolume (pv.yaml):
apiVersion: v1
kind: PersistentVolume
metadata:
name: my-pv
spec:
capacity:
storage: 5Gi
volumeMode: Filesystem
accessModes:
- ReadWriteOnce
hostPath:
path: "/mnt/data"capacity: Specifies the size of the volume.accessModes: Defines how the volume can be accessed.hostPath: In this simple example, we're using a directory on the node's filesystem for storage. In a production environment, you'd typically use a network storage solution.
A PersistentVolumeClaim (pvc.yaml):
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 2GiaccessModes: Must match the access mode of the PV.resources.requests.storage: The amount of storage being requested.
To create them, you would use kubectl apply -f pv.yaml and kubectl apply -f pvc.yaml. Kubernetes will then bind my-pvc to my-pv.
3. Storage Classes: Dynamic Volume Provisioning on the Fly
The Problem: Manual Labor is Tiring 😩
The PV and PVC model is great, but there's a catch in our previous example. The cluster administrator had to manually create the PersistentVolume. This is called static provisioning. Imagine having to manually create a PV every time a developer needs storage. That's a lot of YAML and not very scalable.
The Solution: Let Kubernetes Do the Work! ✨
This is where StorageClasses come to the rescue. A StorageClass provides a way for administrators to describe the "classes" of storage they offer. These classes might map to different quality-of-service levels, backup policies, or different storage backends.
The real magic of StorageClass is that it enables dynamic volume provisioning. With dynamic provisioning, when a user creates a PersistentVolumeClaim, Kubernetes can automatically provision a PersistentVolume to match it, based on the StorageClass specified in the PVC. This eliminates the need for cluster administrators to pre-provision storage.
How it works:
- The administrator defines one or more
StorageClassobjects. EachStorageClassspecifies a provisioner (likekubernetes.io/aws-ebsorkubernetes.io/gce-pd) and parameters for that provisioner. - A developer creates a
PersistentVolumeClaimand specifies the desiredstorageClassName. - The provisioner defined in the
StorageClasssees the PVC and automatically creates a correspondingPersistentVolumeand the underlying storage in the cloud provider or storage system. - Kubernetes then binds the new PV to the PVC.
Example of a StorageClass:
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: standard
provisioner: kubernetes.io/aws-ebs
parameters:
type: gp2
reclaimPolicy: Retain
allowVolumeExpansion: true
mountOptions:
- debug
volumeBindingMode: Immediateprovisioner: Determines which volume plugin is used for provisioning PVs.parameters: Parameters specific to the provisioner.reclaimPolicy: What happens to the underlying storage when the PV is deleted.Deletewill delete it,Retainwill keep it.allowVolumeExpansion: Allows the volume to be resized.volumeBindingMode:Immediateprovisions the volume as soon as the PVC is created.WaitForFirstConsumerwaits until a pod that uses the PVC is created before provisioning.
Now, a developer can simply create a PVC that references this storage class:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-dynamic-pvc
spec:
accessModes:
- ReadWriteOnce
storageClassName: standard
resources:
requests:
storage: 1GiAnd voilà! A new 1Gi AWS EBS volume will be created automatically.
4. StatefulSets: Running Real-world Databases on Kubernetes
The Problem: Deployments Treat Pods Like Cattle, Not Pets 🐄
Standard Deployments are fantastic for stateless applications. They treat pods as interchangeable and disposable. If a pod dies, the Deployment simply creates a new one with a random name.
But what about stateful applications like databases? They require:
- Stable, unique network identifiers: Other applications need a consistent way to connect to them.
- Stable, persistent storage: Each instance needs its own dedicated storage.
- Ordered, graceful deployment and scaling: We can't just spin up or tear down database replicas randomly.
Deployments don't provide these guarantees.
The Solution: StatefulSets for Our Precious Data Pets 🐾
A StatefulSet is a Kubernetes workload API object used to manage stateful applications. It provides the guarantees that stateful applications need.
Key features of a StatefulSet:
- Stable, Unique Network Identity: Each pod in a StatefulSet gets a predictable name, like
my-db-0,my-db-1, etc. It also gets a stable DNS entry. - Stable, Persistent Storage: StatefulSets use a
volumeClaimTemplatesfield to create a uniquePersistentVolumeClaimfor each pod. This ensures that each pod gets its own persistent volume. - Ordered Deployment and Scaling: Pods are created one at a time, in a specific order (e.g.,
my-db-0thenmy-db-1). When scaling down, pods are terminated in the reverse order. - Ordered, Automated Rolling Updates: Updates are applied to pods in a specific order, ensuring a graceful rollout.
Interesting Fact: The name "StatefulSet" was chosen to reflect that it manages a "set" of stateful pods. The original proposal was called "PetSet," which many in the community still fondly remember.
Example of a StatefulSet:
Here is a simplified example of a StatefulSet for a hypothetical database:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: my-db
spec:
serviceName: "my-db-headless"
replicas: 3
selector:
matchLabels:
app: my-db
template:
metadata:
labels:
app: my-db
spec:
containers:
- name: my-db-container
image: my-database-image:latest
ports:
- containerPort: 5432
name: db-port
volumeMounts:
- name: data
mountPath: /var/lib/mydb/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: "fast-storage"
resources:
requests:
storage: 1GiserviceName: This points to a "headless" service that provides the network identity for the pods.replicas: The number of database instances to run.volumeClaimTemplates: This is the magic part. For each replica, a PVC nameddata-my-db-0,data-my-db-1, etc., will be created based on this template.
By using StatefulSets, you can confidently run your databases and other stateful applications on Kubernetes, knowing they'll have the stability and persistence they need.
📚 Extra Reading & References
- Official Kubernetes Documentation:
Challenge
You are a DevOps engineer tasked with deploying a replicated, stateful key-value store on a Kubernetes cluster. To ensure data persistence and stable network identity for each replica, you must use a StatefulSet.
Your task is to complete the provided YAML manifest for a StatefulSet named key-value-store with the following specifications:
- Replicas: The
StatefulSetshould manage exactly3replicas. - Selector: Configure a
selectorwith amatchLabelsfield to identify the pods it manages. Use the labelapp: kv-store. - Governing Service: Set the
serviceNametokv-store-headless. - Pod Template:
- The pods managed by the
StatefulSetmust have the labelapp: kv-store. - The container within the pod should be named
kv-store. - Use the container image
my-kv-store:1.0. - Expose
containerPort6379.
- The pods managed by the
- Persistent Storage:
- Define a
volumeClaimTemplatessection to dynamically provision storage for each replica. - The
PersistentVolumeClaimtemplate should be nameddata. - It must request
1Giof storage. - The storage must have an
accessModesofReadWriteOnce. - It should request storage from the
StorageClassnamedfast-ssd. - Mount this persistent volume inside the container at the path
/var/lib/kvstore.
- Define a
Expected result
A complete and valid Kubernetes StatefulSet YAML manifest.
The manifest should define a StatefulSet with:
replicasset to3.serviceNameset tokv-store-headless.- A
selectorwithmatchLabelsforapp: kv-store. - A pod template (
spec.template) with a matchingapp: kv-storelabel. - A container named
kv-storeusing themy-kv-store:1.0image and exposing port6379. - A
volumeMountsentry in the container spec, mounting the volume nameddatato/var/lib/kvstore. - A
volumeClaimTemplatessection that defines aPersistentVolumeClaimnameddata. - This claim template should specify
accessModesas["ReadWriteOnce"], request1Giof storage, and use thestorageClassNamefast-ssd.