Storage in StatefulSets
Persistent volume claim can be used for storage in StatefulSets. Either there can be single persistent volume claim for all pods or individual claim for each pod. The former approach is similar to Deployments or Replicasets as shown below,
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: nginx
namespace: learning
spec:
selector:
matchLabels:
type: nginx-router
replicas: 3
template:
metadata:
labels:
type: nginx-router
spec:
containers:
- name: nginx
image: nginx
volumeMounts:
- name: pvc
mountPath: /shared
volumes:
- name: pvc
persistentVolumeClaim:
claimName: nginx-pvc
Here each pod uses the same claim.
For latter case where we want to use different claims for individual pods, we can use spec.volumeClaimTemplates
section as shown below.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: nginx
namespace: learning
spec:
selector:
matchLabels:
type: nginx-router
replicas: 3
template:
metadata:
labels:
type: nginx-router
spec:
containers:
- name: nginx
image: nginx
volumeMounts:
- name: pvc
mountPath: /shared
volumeClaimTemplates:
- metadata:
name: pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 500Mi
This feature of StatefulSets makes kubernetes to create separate claims for all the pods.
Tip
I tried using
spec.volumeClaimTemplate
with Deployments. It did not work 🥲.