Middle — Middle+
How does StatefulSet ensure the preservation of container state after restart or reset?
sobes.tech AI
Answer from AI
StatefulSet in Kubernetes ensures the persistence of container state after restart or reset by using persistent volumes and unique identifiers for each pod. Each pod in a StatefulSet gets a stable name and is bound to its PersistentVolumeClaim, which allows data to be stored outside the container's lifecycle. When the pod is restarted, Kubernetes mounts the same volume, providing access to saved data and application state.
Example:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: example
spec:
serviceName: "example-service"
replicas: 3
selector:
matchLabels:
app: example
template:
metadata:
labels:
app: example
spec:
containers:
- name: example-container
image: example-image
volumeMounts:
- name: data
mountPath: /data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
Here, each pod gets its own volume that preserves data independently of the container's lifecycle.