Version note: examples use the Kubernetes v1.35 documentation snapshot, not necessarily the newest release. Check current support and component compatibility. These commands were not tested on a live cluster.
What this guide covers
A StatefulSet gives Pods stable names and can attach a separate persistent volume to each Pod. A persistent volume keeps files beyond a Pod’s lifetime, but it is not a backup.
Before you start
Create storage-lab in a test cluster. You need a StorageClass that can provide the requested storage. Check its access mode, reclaim policy and whether data can move to another node.
Step 1: Create the StatefulSet
Save this as storage.yaml, then run kubectl apply -f storage.yaml:
apiVersion: v1
kind: Service
metadata:
name: journal
namespace: storage-lab
spec:
clusterIP: None
selector:
app: journal
ports:
- name: http
port: 80
targetPort: http
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: journal
namespace: storage-lab
spec:
serviceName: journal
replicas: 1
selector:
matchLabels:
app: journal
template:
metadata:
labels:
app: journal
spec:
containers:
- name: web
image: nginx:1.28.0
ports:
- name: http
containerPort: 80
volumeMounts:
- name: content
mountPath: /usr/share/nginx/html
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
memory: 128Mi
volumeClaimTemplates:
- metadata:
name: content
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
The headless Service supports stable Pod DNS names. volumeClaimTemplates creates storage claims for each Pod. Wait for the claim to bind and the Pod to become Ready.
Step 2: Write a file and replace the Pod
Run:
kubectl -n storage-lab get statefulset,pod,pvc
kubectl get pv
kubectl -n storage-lab exec journal-0 -- sh -c \
'printf "persistent lab content\n" > /usr/share/nginx/html/index.html'
kubectl -n storage-lab delete pod journal-0
kubectl -n storage-lab wait --for=condition=Ready pod/journal-0 --timeout=180s
kubectl -n storage-lab exec journal-0 -- cat /usr/share/nginx/html/index.html
This writes only test content. After the Pod returns, read the file again. The same volume should be attached to the replacement Pod.
Step 3: Check storage before maintenance
If the replacement is Pending, inspect its claim and events. A local disk may tie the Pod to one node; a volume does not automatically make data portable or replicate a database. Take application-consistent backups before testing destructive operations.
Check the result
The file should survive Pod replacement. Check reclaim and retention policies before deleting the StatefulSet, namespace or claims: deleting a storage claim may delete the underlying data.
Conversation
0 commentsNo comments yet. Start the conversation below.