In the previous article of the series, Basics on Kubernetes we talked about deployments in Kubernetes. You can read about it at the below link. In this article, we are going to talk about statefulsets, their similarity, and differences with deployments.
What exactly is a Statefulset?
Statefulsets are like deployments, they also manage pods that are given the same specs. But statefulsets identify their pods separately, which means even they are created from the same spec they are not interchangeable as the case with deployments. So statefulset can be used in the place where you need to identify each pod as different.
Pods in statefulsets are deleted in order so that is useful in the maintenance of critical stateful systems running on Kubernetes.
Where you can use statefulsets?
A few examples where they can be used are persistent storage, identify pods on the network, ordered deployment, and ordered rollout.
This also means that you can use statefulsets to run your databases by using persistent volumes. You can run master-slave models etc with persistent volume and every time a pod gets deleted it will be attached with the same volume and data will be back. You may need to add some scripts to automate these recovery mechanisms.
So in short with statefulset you can create a set of pods that have their own identity and their network, volume, etc can be tied to the pods themselves, even when they restart. Here is a small example of a manifest of statefulset.
apiVersion: apps/v1 kind: StatefulSet metadata: name: web spec: serviceName: "nginx" replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: k8s.gcr.io/nginx-slim:0.8 ports: - containerPort: 80 name: web volumeMounts: - name: www mountPath: /usr/share/nginx/html volumeClaimTemplates: - metadata: name: www spec: accessModes: [ "ReadWriteOnce" ] resources: requests: storage: 1Gi
If you look at the yaml it is very similar to depoyment. Just the kind is different. But with statefulsets the pods that are launched are managed differently.
You can read more about statefulsets here.
If you like the article please share and subscribe. We also have another website if you need help with Guidance on DevOps and SRE preparation.