Managing Kubernetes State with Persistent Volumes
Introduction to Persistent Volumes (PVs)
In Kubernetes, a Persistent Volume (PV) is a storage resource that persists data beyond the lifecycle of a Pod. This is useful for applications that require persistent storage, like databases. A PV is provisioned either manually by an administrator or dynamically using storage classes.
PV Lifecycle and States
- Available: A volume that’s ready to be claimed.
- Bound: A volume bound to a Persistent Volume Claim (PVC).
- Released: The PVC has been deleted, but the resource is not reclaimed by the cluster.
- Failed: Automatic recovery failed; manual intervention is needed.
apiVersion: v1
kind: PersistentVolume
metadata:
name: my-pv
status:
phase: Available
Access Modes
- ReadWriteOnce (RWO): The volume can be mounted read-write by a single node.
- ReadOnlyMany (ROX): The volume can be mounted read-only by multiple nodes.
- ReadWriteMany (RWX): The volume can be mounted as read-write by multiple nodes.
Reclaim Policies
- Retain: Keeps the data in the PV after PVC is deleted.
- Delete: Deletes the PV and the underlying storage upon PVC deletion.
- Recycle: Deprecated; used to scrub data before becoming available again.
Storage Classes
A Storage Class defines how a PV should be provisioned. It sets the provisioner, parameters, and reclaim policy for dynamic volume allocation.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: my-storage-class
provisioner: kubernetes.io/aws-ebs
parameters:
type: gp2
reclaimPolicy: Retain
Dynamic Provisioning
When a PVC request can’t be fulfilled by existing PVs, a new PV is dynamically provisioned based on a Storage Class.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-pvc
spec:
storageClassName: my-storage-class
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
Troubleshooting Exercise
Setup Commands
-
Create a Storage Class
kubectl apply -f my-storage-class.yaml
-
Create a Persistent Volume Claim
kubectl apply -f my-pvc.yaml
Exercise
Your Persistent Volume Claim is stuck in the Pending
state. Find out why and resolve the issue.
Debugging
-
Check the status of the PVC
kubectl get pvc my-pvc
-
Describe the PVC for more details
kubectl describe pvc my-pvc
-
Check logs or events (if applicable)
kubectl get events --sort-by=.metadata.creationTimestamp
Solution
If the PVC is stuck in Pending
, it’s possible that the storage class is misconfigured or there are no available resources. Check the describe
output and events for clues. You might need to edit or recreate the Storage Class and/or PVC with correct configurations.
kubectl edit storageclass my-storage-class
kubectl delete pvc my-pvc
kubectl apply -f my-pvc.yaml