What is persistent storage?
Ensuring data persistence in Kubernetes is vital to maintain application state and preserving data during pod restarts & failures. In this section, we will go over an explanation on how to establish persistent storage in Kubernetes using Persistent Volumes (PV) and Persistent Volume Claims (PVC).
Through the utilization of these resources, we are able to separate storage from the temporary pods, which will enable data to remain intact regardless of the pod's lifespan. We will create a PV, bind it to a PVC, deploy a Redis instance that uses persistent storage, delete the pods, and observe how the data remains intact throughout the process.
- We begin by creating a YAML file for the persistent volume we can name this file as you wish, i will name it Redis.YAML
apiVersion: v1
kind: PersistentVolume
metadata:
name: redis-pv
spec:
storageClassName: ""
capacity:
storage: 1Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/mnt/data"
We will save it and perform the following command:
kubectl apply -f redis.yaml
We can verify its creation by performing.
kubectl get kv
Next, we will create a persistentvolumeclaim.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: redisdb-pvc
spec:
storageClassName: ""
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
Save the file as persistentvolumeclaim.yaml
kubectl apply -f persistentvolumeclaim.yaml
We can once again verify this by running.
kubectl get pvc
Create the redispod image, with a mounted volume to mount path `/data`
apiVersion: v1
kind: Pod
metadata:
name: redispod
spec:
containers:
- image: redis
name: redisdb
volumeMounts:
- name: redis-data
mountPath: /data
ports:
- containerPort: 6379
protocol: TCP
volumes:
- name: redis-data
persistentVolumeClaim:
claimName: redisdb-pvc
Save it as redispod.yaml.
Next, perform the following command to execute the pod:
kubectl apply -f redispod.yaml
Now let's connect to the container to write some data.
kubectl exec -it redispod – redis-cli
We will now set the server name by executing the following commands:
SET server:name "redis server"
GET server:name
QUIT
Now let's verify that this data we just wrote resides on the volume rather than the pod
- We will delete the pod.
kubectl delete pod redispod
- We will create a new pod by editing the redispod.yaml we had earlier and editing the pod name to "redispod2", it should look like this:
apiVersion: v1
kind: Pod
metadata:
name: redispod2
spec:
containers:
- image: redis
name: redisdb
volumeMounts:
- name: redis-data
mountPath: /data
ports:
- containerPort: 6379
protocol: TCP
volumes:
- name: redis-data
persistentVolumeClaim:
claimName: redisdb-pvc
- We will create the redispod2.
kubectl apply -f redispod.yaml
Once redispo2 is created, we should verify that the data is saved on the volume, and we should get the values we had established before: