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

  1. Available: A volume that’s ready to be claimed.
  2. Bound: A volume bound to a Persistent Volume Claim (PVC).
  3. Released: The PVC has been deleted, but the resource is not reclaimed by the cluster.
  4. Failed: Automatic recovery failed; manual intervention is needed.
apiVersion: v1
kind: PersistentVolume
metadata:
  name: my-pv
status:
  phase: Available

Access Modes

  1. ReadWriteOnce (RWO): The volume can be mounted read-write by a single node.
  2. ReadOnlyMany (ROX): The volume can be mounted read-only by multiple nodes.
  3. ReadWriteMany (RWX): The volume can be mounted as read-write by multiple nodes.

Reclaim Policies

  1. Retain: Keeps the data in the PV after PVC is deleted.
  2. Delete: Deletes the PV and the underlying storage upon PVC deletion.
  3. 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

  1. Create a Storage Class

    kubectl apply -f my-storage-class.yaml
    
  2. 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

  1. Check the status of the PVC

    kubectl get pvc my-pvc
    
  2. Describe the PVC for more details

    kubectl describe pvc my-pvc
    
  3. 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