Kubernetes Persistent Volume Lab (HostPath)

This lab demonstrates:


Architecture

Pod
 |
 +-- PVC (block-pvc)
        |
        +-- PV (block-pv)
                |
                +-- hostPath: /lab154

The actual file will be stored on the node in:

/lab154

Step 1 - Create the Persistent Volume

Create a file named pv.yaml.

apiVersion: v1
kind: PersistentVolume
metadata:
  name: block-pv
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: /lab154

Apply it:

kubectl apply -f pv.yaml

Verify:

kubectl get pv

Expected:

NAME       CAPACITY   ACCESS MODES   STATUS
block-pv   10Gi       RWO            Available

Step 2 - Create the Persistent Volume Claim

Create pvc.yaml.

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

Apply:

kubectl apply -f pvc.yaml

Verify:

kubectl get pvc
kubectl get pv

Expected:

PVC STATUS = Bound
PV STATUS  = Bound

Step 3 - Create a Pod that Uses the Claim

Create pod.yaml.

apiVersion: v1
kind: Pod
metadata:
  name: storage-test
spec:
  containers:
  - name: busybox
    image: busybox
    command: ["sh", "-c", "sleep 3600"]

    volumeMounts:
    - name: data
      mountPath: /data

  volumes:
  - name: data
    persistentVolumeClaim:
      claimName: block-pvc

Apply:

kubectl apply -f pod.yaml

Verify:

kubectl get pods

Wait until:

storage-test   Running

Step 4 - Write Data to the Volume

Open a shell inside the Pod:

kubectl exec -it storage-test -- sh

Create a file:

echo "Jan was here" > /data/proof.txt

Verify:

cat /data/proof.txt

Expected:

Jan was here

Exit the shell:

exit

Step 5 - Verify from Outside the Pod

Read the file directly:

kubectl exec storage-test -- cat /data/proof.txt

Expected:

Jan was here

Step 6 - Prove Persistence

Delete the Pod:

kubectl delete pod storage-test

Recreate it:

kubectl apply -f pod.yaml

Wait until Running again:

kubectl get pod

Read the file:

kubectl exec storage-test -- cat /data/proof.txt

You should still see:

Jan was here

This proves the data survived the Pod deletion.


Step 7 - Verify from the Node

Because this is a hostPath volume, the file actually exists on the worker node.

sudo ls /lab154

Expected:

proof.txt

Display contents:

sudo cat /lab154/proof.txt

Expected:

Jan was here

CKA Exam Notes

Remember:


Useful Troubleshooting Commands

kubectl get pv
kubectl get pvc
kubectl describe pv block-pv
kubectl describe pvc block-pvc
kubectl describe pod storage-test

What to Remember for the CKA

PV Available --> PVC Created --> Bound

Pod
  -> PVC
      -> PV
          -> Storage

Never:
Pod -> PV

Always:
Pod -> PVC -> PV