What is a StatefulSet?

I am a Site Reliability Engineer with nearly 5 years of experience. I talk about Linux, Automation, Networking, and anything else related to tech and CS.
A stateful set is a Kubernetes object that manages a set of pods that need to maintain persistent storage. The StatefulSet ensures that each pod in the set has a unique identity and that the pods are always started in the same order.
A StatefulSet is a Kubernetes object used to manage stateful applications. It is designed to manage stateful applications by creating and managing a set of replica Pods, each of which has a unique network identity and persistent storage. Each Pod in a StatefulSet is created sequentially, and each Pod is assigned a unique hostname that is based on its position in the StatefulSet.
StatefulSets are useful for running stateful applications such as databases, key-value stores, and message brokers, where each instance has a unique identity and requires persistent storage. StatefulSets can provide stable network identities and persistent storage for these applications.
Here is an example scenario where a StatefulSet can be used:
Let's say you have a stateful application like a database that requires a specific amount of storage and a specific network identity. You want to run this application on Kubernetes to take advantage of its container orchestration capabilities, but you also need to ensure that the application's data is stored persistently and that each instance of the application has a unique identity.
In this scenario, you can use a StatefulSet to manage the database instances. The StatefulSet will create and manage a set of replica Pods, each of which has a unique network identity and persistent storage. Each instance of the database will be created sequentially and will have a unique hostname based on its position in the StatefulSet.
An example of a StatefulSet configuration file is as follows:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: database
spec:
serviceName: database
replicas: 3
selector:
matchLabels:
app: database
template:
metadata:
labels:
app: database
spec:
containers:
- name: database
image: your-database-image:latest
ports:
- containerPort: 5432
volumeMounts:
- name: database-storage
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: database-storage
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 10Gi




