Day 36: Managing Persistent volume in your deployments

U

Udoh Deborah

Guest
On Day 36 of your #90DaysOfDevOps journey, we’re tackling an important part of Kubernetes: Persistent Volumes (PVs)

Let’s break this down and walk you through both tasks:

What are Persistent Volumes (PV) in Kubernetes?

Kubernetes Pods are ephemeral β€” which means data inside a Pod is lost when the Pod is deleted or restarted. To persist data beyond the lifecycle of a Pod, we use:
β€’ Persistent Volumes (PV): Storage resource in the cluster, provisioned by admins or dynamically via StorageClass.
β€’ Persistent Volume Claims (PVC): A request for storage by a user or app.
β€’ Deployment + PVC: Your app (e.g., the ToDo app) can claim storage by referencing a PVC.

Task 1: Add Persistent Volume to Your Deployment

Let’s go step-by-step.

  1. Create a Persistent Volume (pv.yml)

apiVersion: v1
kind: PersistentVolume
metadata:
name: todo-pv
spec:
capacity:
storage: 1Gi
accessModes:
- ReadWriteOnce
hostPath:
path: /mnt/data

This creates a 1Gi volume using the hostPath /mnt/data on the node (local path for testing).

  1. Create a Persistent Volume Claim (pvc.yml)

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

This PVC will bind to the todo-pv if the specs match.

  1. Update your deployment.yml to use the PVC

Here’s the updated Deployment with volume mounting:

apiVersion: apps/v1
kind: Deployment
metadata:
name: todo-app
spec:
replicas: 1
selector:
matchLabels:
app: todo
template:
metadata:
labels:
app: todo
spec:
containers:
- name: todo-container
image: your-todo-app-image
volumeMounts:
- name: todo-storage
mountPath: /app/data
volumes:
- name: todo-storage
persistentVolumeClaim:
claimName: todo-pvc

Make sure:
β€’image: your-todo-app-image is replaced with your actual image.
β€’/app/data is where your app stores persistent data.

  1. Apply the files

kubectl apply -f pv.yml
kubectl apply -f pvc.yml
kubectl apply -f deployment.yml

  1. Verify Everything

kubectl get pv
kubectl get pvc
kubectl get pods

Look for STATUS: Bound on the PVC and Running pods.

Task 2: Access Data Inside the Pod

  1. Connect to the Pod

kubectl get pods # get pod name
kubectl exec -it -- /bin/bash

  1. Verify Data Access

cd /app/data
ls -l

OR​


cat

You should see files created or used by your app.

Optional: Test Persistence
1. Delete the pod:

kubectl delete pod


Code:
2.  A new pod will be created (Deployment ensures this).
3.  Check if data is still present by repeating the steps to access /app/data.

You have Created and attached a Persistent Volume.

Continue reading...
 


Join 𝕋𝕄𝕋 on Telegram
Channel PREVIEW:
Back
Top