Sunday 18 July 2021

Persistent Volumes (PV) Storing Files in Kubernetes

We can go through the definition of PV and PVC First. 


A PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator or dynamically provisioned using Storage Classes. It is a resource in the cluster just like a node is a cluster resource. 


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). Claims can request specific size and access modes (e.g., they can be mounted ReadWriteOnce, ReadOnlyMany, or ReadWriteMany, see AccessModes).


These are the definitions from the K8s, In short, then Persistent volumes provide the space where we can store the files required for the functioning of our application.


Suppose consider my requirement. Where I need to store the huge shell scripts files, then I need to use them for the cron job to trigger. A persistent volume is one of the ways to do it.

This is one of the approaches to achieve it, there are also other ways where we can achieve this.


We cannot access the persistent volume without the persistent claim. Hence while creating the Persistent volume, we are also asked to create the Persistent claim also.


This Persistent volume remains even after the Pod is deleted.


Step:1 Persistent Volume creation in K8's.


apiVersion: v1

kind: PersistentVolume

metadata:

  name: scripts-pv-volume

  labels:

    type: local

spec:

  storageClassName: manual

  capacity:

    storage: 10Gi

  accessModes:

    - ReadWriteOnce

  hostPath:

    path: "/opt/data"

Step:2 Create the Persistent Volume claim


apiVersion: v1

kind: PersistentVolumeClaim

metadata:

  name: scripts-pv-claim

spec:

  storageClassName: manual

  accessModes:

    - ReadWriteOnce

  resources:

    requests:

      storage: 3Gi

    

Step:3 Use the Storage.


Copy the script files to the "/opt/data" persistent volume by the below command.


kubectl cp welcome.ksh default/mypod:/opt/data


where default is the namespace.

my pod is the name of my pod.

/opt/data is the path where this file needs to be copied.


apiVersion: batch/v1beta1

kind: CronJob

metadata:

  name: welcome-jobs

spec:

  replicas: 2

  selector:

    matchLabels:

      app: welcome-jobs

  template:

    metadata:

      labels:

        app: welcome-jobs

    spec:

      volumes:

        - name: scripts-pv-storage

          persistentVolumeClaim:

            claimName: scripts-pv-claim

      containers:

        - name: scripts-pv-container

          image: busybox

  command: ["/opt/data/welcome.ksh"]

          volumeMounts:

            - mountPath: "/opt/data"

              name: scripts-pv-storage


This will execute the Script welcome.ksh from the location /opt/data.


Happy Learning !!!!


No comments:
Write comments