Unlocking Persistent Storage in Kubernetes: A Guide to PVs, PVCs, and Deployments

Unlocking Persistent Storage in Kubernetes: A Guide to PVs, PVCs, and Deployments

Managing persistent storage is a critical part of running stateful applications in Kubernetes. Here's a quick overview of how to set up persistent storage using a PersistentVolume (PV), a PersistentVolumeClaim (PVC), and a Deployment.

1. PersistentVolume (PV)

A PersistentVolume is a cluster resource that provides storage to pods. Here is an example configuration:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: example-pv
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: standard
  hostPath:
    path: "/mnt/data"

Key Points:

  • capacity: Defines the storage size (1Gi in this case).

  • accessModes: Specifies how the volume can be mounted (e.g., ReadWriteOnce).

  • persistentVolumeReclaimPolicy: Retain the data even after PVC deletion.

  • hostPath: Maps the PV to a directory on the host node.


2. PersistentVolumeClaim (PVC)

A PVC allows pods to request specific storage resources dynamically.

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

Key Points:

  • resources.requests: Specifies the amount of storage required.

  • storageClassName: Matches the PV’s storage class.


3. Deployment Using the PVC

In this example, an Nginx Deployment uses the storage defined by the PVC.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        volumeMounts:
        - name: storage-volume
          mountPath: /usr/share/nginx/html
      volumes:
      - name: storage-volume
        persistentVolumeClaim:
          claimName: example-pvc

Key Points:

  • volumeMounts: Mounts the PVC to /usr/share/nginx/html in the container.

  • volumes: Connects the Deployment to the PVC.

To use these:

  1. Apply PV first: kubectl apply -f pv.yaml

  2. Apply PVC: kubectl apply -f pvc.yaml

  3. Apply Deployment: kubectl apply -f deployment.yaml

Check status:


kubectl get pv
kubectl get pvc
kubectl get pods

Conclusion

This configuration ensures that your application has persistent storage, even if the pod is deleted or recreated. The PV provides the actual storage, the PVC claims it, and the Deployment uses it.