In Kubernetes, a StatefulSet is a controller object used for managing stateful applications. It is similar to a Deployment in that it manages a set of replicated Pods, but it is designed specifically for applications that require stable, unique network identities and persistent storage. This is particularly useful for stateful applications such as databases or message brokers that require stable hostnames or storage volumes.
Unlike Deployments, StatefulSets guarantee a unique identity and stable hostname for each Pod they manage. This is achieved by using a stable network identity for each Pod based on its ordinal index. For example, if a StatefulSet is managing three replicas, the first Pod will have a stable hostname of pod-0, the second will have a hostname of pod-1, and so on. This allows stateful applications to be deployed and scaled while maintaining consistent network identities.
Another key difference between StatefulSets and Deployments is in how they manage persistent storage. Deployments assume that their Pods are stateless and can be terminated and replaced at any time without loss of data. StatefulSets, on the other hand, assume that their Pods are stateful and require persistent storage to maintain data. As a result, each Pod in a StatefulSet is assigned a unique persistent volume claim (PVC) that is not deleted when the Pod is terminated.
Overall, StatefulSets are a powerful tool for managing stateful applications in Kubernetes, providing stable network identities and persistent storage. However, they are more complex to manage than Deployments and require careful consideration of the underlying infrastructure and application requirements.
Example:
Here is an example of a simple StatefulSet definition for running a stateful application such as a database:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: db
spec:
selector:
matchLabels:
app: db
serviceName: "db"
replicas: 3
template:
metadata:
labels:
app: db
spec:
containers:
- name: db
image: mydb:latest
ports:
- containerPort: 5432
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 1Gi
In this example, the StatefulSet manages a set of three replicas of a database container. Each replica is assigned a unique network identity based on its ordinal index (db-0, db-1, db-2). The container is configured with a persistent volume mount at /var/lib/postgresql/data using a volume claim template that ensures each replica has its own unique storage volume.