Introduction to Persistent Volume Claims (PVCs)

Persistent Volume Claims (PVCs) in Kubernetes are used to manage storage resources. They act as a request for storage and abstract the underlying implementation details like NFS, AWS EBS, etc.

Creating and Using PVCs

To create a PVC, you’ll need a YAML file that describes its specifications.

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi

Use kubectl to create it:

kubectl apply -f my-pvc.yaml

To use the PVC in a Pod:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - name: my-container
    image: nginx
    volumeMounts:
    - mountPath: "/data"
      name: my-volume
  volumes:
  - name: my-volume
    persistentVolumeClaim:
      claimName: my-pvc

Binding and Storage Class Considerations

Once a PVC is created, Kubernetes will try to find a suitable Persistent Volume (PV) to bind it to. The binding is governed by StorageClass.

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: fast-storage
provisioner: kubernetes.io/aws-ebs
parameters:
  type: gp2

PVC Lifecycle

  1. Provisioning: Created by user
  2. Binding: Binds to a suitable PV
  3. Using: Used by a Pod
  4. Releasing: Unbound from the Pod
  5. Reclaiming: PV is either recycled, deleted, or retained based on reclaim policy

Best Practices

  1. Clearly Define Resources: Always specify storage size and access modes.
  2. Use Labels: Make it easier to manage PVCs with labels.
  3. Reuse PVCs: If possible, design applications so PVCs can be reused.
  4. Choose the Right Storage Class: Ensure you choose a storage class that meets your performance and budget requirements.

Exercise: Setting up and Using a PVC

Setup

  1. Create a StorageClass:
kubectl apply -f storage-class.yaml
  1. Create a PVC:
kubectl apply -f my-pvc.yaml

Steps

  1. Check PVC status:
kubectl get pvc my-pvc
  1. Create a Pod using the PVC:
kubectl apply -f my-pod.yaml
  1. Verify Pod and PVC binding:
kubectl describe pod my-pod

Troubleshooting

  1. PVC not Bound: Check events in the PVC description (kubectl describe pvc my-pvc)
  2. Pod Errors: Look at Pod logs (kubectl logs my-pod)

Solution

If everything is set up correctly, your Pod should be running, and the PVC should be bound to a PV.