What are persistent volumes in K8s?
In Kubernetes, a Persistent Volume (PV) is a piece of storage in the cluster that has been provisioned by an administrator. A Persistent Volume Claim (PVC) is a request for storage by a user. The PVC references the PV, and the PV is bound to a specific node.
What is persistent volume claim?
A PersistentVolumeClaim (PVC) is a request for storage by a user. It is similar to a Pod. Pods consume node resources and PVCs consume PV resources. Pods can request specific levels of resources (CPU and Memory).
A user creates, or in the case of dynamic provisioning, has already created, a PersistentVolumeClaim with a specific amount of storage requested and with certain access modes. A control loop in the control plane watches for new PVCs, finds a matching PV (if possible), and binds them together.
Basically creating only Pv(persistent volume) is not enough you need to claim that volume using PVC.
Task 1:
Create a Persistent Volume using a file on your node.
apiVersion: v1 kind: PersistentVolume metadata: name: mysql-pv-volume namespace: mysql labels: app: mysql spec: storageClassName: manual capacity: storage: 2Gi accessModes: - ReadWriteOnce hostPath: path: /mnt/volumne
Use the command to check persistent volume is created :
kubectl get pv -n mysql
Create a Persistent Volume Claim that references the Persistent Volume.
apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mysql-pv-claim namespace: mysql spec: storageClassName: manual accessModes: - ReadWriteOnce resources: requests: storage: 1Gi
kubectl get pvc -n mysql
You'll see that the status is Bound , it means you've successfully claimed the volume.
Update your deployment.yml file to include the Persistent Volume Claim. After Applying pv.yml pvc.yml your deployment file look.
apiVersion: apps/v1 kind: Deployment metadata: name: mysql namespace: mysql labels: app: mysql spec: replicas: 1 selector: matchLabels: app: mysql template: metadata: labels: app: mysql spec: containers: - name: mysql image: mysql:8 ports: - containerPort: 3306 env: - name: MYSQL_ROOT_PASSWORD valueFrom: secretKeyRef: name: mysql-secret key: password - name: MYSQL_DATABASE valueFrom: configMapKeyRef: name: mysql-config key: MYSQL_DB volumeMounts: - name: mysql-persistent-storage mountPath: /var/lib/mysql volumes: - name: mysql-persistent-storage persistentVolumeClaim: claimName: mysql-pv-claim
Apply the updated deployment using the command:
kubectl apply -f deployment.yml
Task 2:
Connect to a Pod in your Deployment using the command :
kubectl exec -it -- /bin/bash
Conclusion:
Persistent Volumes and Persistent Volume Claims are the cornerstones of managing stateful applications in a Kubernetes environment. By understanding how to set up, utilize, and manage these resources, you can ensure that your applications remain stateful, even in the transient world of Kubernetes.