Can you explain how StatefulSet differs from Deployment in Kubernetes and what tasks it is used for?
sobes.tech AI
Answer from AI
StatefulSet and Deployment are controllers in Kubernetes that manage the deployment of pods, but they are designed for different scenarios.
-
Deployment is used for stateless applications. It provides scaling, updating, and rollback of pod versions, and all pods are considered interchangeable and do not have persistent identities.
-
StatefulSet is intended for stateful applications, where a stable identity, persistent storage, and ordered deployment/termination are important. Examples include databases, caches, and distributed systems.
Main differences:
- Each pod in StatefulSet gets a unique, stable network identity (hostname).
- Pods are created and deleted in a specific order.
- Persistent storage (PersistentVolume) is associated with each pod.
Example: deploying a MongoDB cluster where each node must have a persistent identity and data.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mongo
spec:
serviceName: "mongo"
replicas: 3
selector:
matchLabels:
app: mongo
template:
metadata:
labels:
app: mongo
spec:
containers:
- name: mongo
image: mongo:4.2
volumeMounts:
- name: mongo-persistent-storage
mountPath: /data/db
volumeClaimTemplates:
- metadata:
name: mongo-persistent-storage
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10Gi
Thus, Deployment is suitable for scalable stateless applications, while StatefulSet is for applications where state preservation and uniqueness are critical.