Middle
For which application should StatefulSet be used instead of Deployment and why?
sobes.tech AI
Answer from AI
StatefulSet should be used for applications that require:
- Stable network identity. Pods receive a unique, persistent hostname in the format
<statefulset-name>-<pod-index>. - Stable, persistent storage. Each Pod replica is assigned its own PersistentVolume. Even upon Pod restart, its data remains attached.
- Ordered deployment and scaling. Pods are created and deleted in a strictly defined order (ascending for creation, descending for deletion).
- Ordered or parallel updates. Supports both gradual (rolling update) and parallel (in-place or parallel) updates, with the ability to control the order.
Examples of such applications:
- Databases (MySQL, PostgreSQL, MongoDB)
- Message brokers (Kafka, RabbitMQ)
- Cache systems (Redis, Memcached)
- Distributed file systems (e.g., Ceph, if running in Kubernetes)
- Any application that needs to preserve state across restarts and have a stable identity.
Unlike Deployment, where Pods are interchangeable and stateless, StatefulSet guarantees uniqueness and state preservation for each replica, which is critical for applications dependent on persistent storage and stable network identity.
An example of a simple StatefulSet for a database:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mysql
spec:
selector:
matchLabels:
app: mysql
serviceName: "mysql" # Necessary for stable network identity of Pods
replicas: 3
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:5.7
ports:
- containerPort: 3306
env:
- name: MYSQL_ROOT_PASSWORD
value: "password" # Use Secrets in production
volumeMounts:
- name: mysql-persistent-storage
mountPath: /var/lib/mysql # Path where persistent storage is mounted
volumeClaimTemplates:
- metadata:
name: mysql-persistent-storage # PVC template name
spec:
accessModes: [ "ReadWriteOnce" ] # Access mode
resources:
requests:
storage: 10Gi # Requested storage size