(June 24) DevOps: Assigning Permanent Volume in a Kubernetes Cluster: A Brief Guide
In Kubernetes, persistent storage is essential for applications that require data to persist beyond the lifecycle of individual pods. Persistent Volumes (PVs) and Persistent Volume Claims (PVCs) provide a way to manage durable storage in a Kubernetes cluster. This article will explain how to assign a permanent volume in Kubernetes with an example.
Understanding Persistent Volumes and Claims
Persistent Volume (PV): A piece of storage in the cluster that has been provisioned by an administrator or dynamically using a StorageClass.
Persistent Volume Claim (PVC): A request for storage by a user. It's similar to a pod that consumes node resources.
Step-by-Step Example
1. Create a Persistent Volume (PV)
First, define a Persistent Volume in a YAML file. This specifies the storage properties and how it is provisioned.
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv-example
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: manual
hostPath:
path: "/mnt/data"In this example:
capacity.storagespecifies the size of the volume.accessModesspecifies that the volume can be mounted as read-write by a single node.persistentVolumeReclaimPolicyis set toRetainto keep the data even after the PVC is deleted.hostPath.pathspecifies the directory on the host.
Save this as pv.yaml and create the PV:
kubectl apply -f pv.yaml2. Create a Persistent Volume Claim (PVC)
Next, define a Persistent Volume Claim that matches the specifications of the PV.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pvc-example
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
storageClassName: manualSave this as pvc.yaml and create the PVC:
kubectl apply -f pvc.yaml3. Use the PVC in a Pod
Create a pod that uses the PVC. Define the pod in a YAML file.
apiVersion: v1
kind: Pod
metadata:
name: pod-using-pvc
spec:
containers:
- name: mycontainer
image: nginx
volumeMounts:
- mountPath: "/usr/share/nginx/html"
name: mypvc
volumes:
- name: mypvc
persistentVolumeClaim:
claimName: pvc-exampleSave this as pod.yaml and create the pod:
kubectl apply -f pod.yamlThis pod uses the PVC named pvc-example, and mounts it at /usr/share/nginx/html in the container.
Verifying the Setup
1. Check Persistent Volumes
kubectl get pv2. Check Persistent Volume Claims
kubectl get pvc3. Check Pods
kubectl get pods4. Describe the Pod
kubectl describe pod pod-using-pvcConclusion
Assigning a permanent volume in a Kubernetes cluster involves creating a Persistent Volume (PV), a Persistent Volume Claim (PVC), and then using the PVC in a pod. This process ensures that data persists independently of the pod lifecycle, providing a durable and reliable storage solution. By following the steps outlined in this article, you can effectively manage persistent storage in your Kubernetes environment.