Middle
What is the difference between Deployment and StatefulSet in Kubernetes?
sobes.tech AI
Answer from AI
Deployment and StatefulSet are controllers in Kubernetes that manage the deployment of pods, but they are designed for different scenarios.
Deployment is used for managing stateless applications, where pods are interchangeable and do not preserve state. It provides scaling, updating, and version rollback without binding to specific instances.
StatefulSet is intended for stateful applications that require a stable identifier, startup order, and state preservation. Each pod in a StatefulSet gets a unique name and persistent storage, which is important for databases, cache systems, and other stateful services.
Examples of differences:
- Deployment: web servers, API servers
- StatefulSet: databases (e.g., Cassandra, MongoDB), Kafka
Key differences:
- Pod names: Deployment — random, StatefulSet — stable and predictable
- Data storage: StatefulSet supports PersistentVolume for each pod
- Creation and deletion order: StatefulSet guarantees sequence
# Example of StatefulSet with persistent storage
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: example
spec:
serviceName: "example"
replicas: 3
selector:
matchLabels:
app: example
template:
metadata:
labels:
app: example
spec:
containers:
- name: example
image: example-image
volumeMounts:
- name: data
mountPath: /data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi