When creating a StatefulSet, the pods will be created in sequential order. This means that the first pod will be created with the name
my-stateful-app-0, the second one with the name
my-stateful-app-1, and so on. The maximum number is equal to the number of replicas you have specified in the StatefulSet. This differs from a ReplicaSet, where the pods are simultaneously created in a random order.
The StatefulSet starts with the lowest
index and waits for the pod to be ready. Only then will it create the next pod. This ensures that the pods are created in sequential order and that the current pod is ready before the next one is being created. You can also attach persistent storage to the stateful pod. This ensures that the data of the pod is stored on persistent storage and that the data is not lost when the pod is deleted. This is useful, for example, when you have a database that has to persist data. If the database pod crashes or is deleted, the data is still available on the persistent storage.
A manifest for a StatefulSet might look like this:
- name: my-stateful-app
- containerPort: 8080
An important part to consider is the definition of the service for a StatefulSet as a so-called
headless service. When using a service that load balances traffic to pods managed by a ReplicaSet, the service identifies the pods by their labels, as the pods are assigned a random hash at the end of their name. With StatefulSets, on the other hand, the pods are identified by their stable names, such as
my-stateful-app-1. In this context, it's not required to have a load balancer with one IP address as a service to load balance traffic to randomly named pods.
A manifest for a Headless Service might look like this:
clusterIP: None # this makes the service headless
- name: web
clusterIP is set to
None, which makes the service
headless in Kubernetes. This means that the service will not have a cluster IP.
In this lesson, you learned about StatefulSets in Kubernetes and that StatefulSets are used to deploy stateful applications, such as databases or message brokers. You can now also differentiate StatefulSets from ReplicaSets, since they create pods in sequential order with an unique index and a stable name. Additionally, you learned that you can use a
headless service to connect to the pods of a StatefulSet.