Sure shot question 6: Creating a PersistentVolume, PersistentVolumeClaim, and Deployment in Kubernetes

Question Format

 

Create a new PersistentVolume named web-pv. It should have a capacity of 2Gi, accessMode ReadWriteOnce, hostPath /vol/data and no storageClassName defined. Next create a new PersistentVolumeClaim in Namespace production named web-pvc . It should request 2Gi storage, accessMode ReadWriteOnce and should not define a storageClassName. The PVC should bound to the PV correctly. Finally create a new Deployment web-deploy in Namespace production which mounts that volume at /tmp/web-data. The Pods of that Deployment should be of image nginx:1.14.2

 

Step 1: Create the PersistentVolume

YAML Definition

Create a file named web-pv.yaml:

apiVersion: v1
kind: PersistentVolume
metadata:
 name: web-pv
spec:
 capacity:
   storage: 2Gi
 accessModes:
   - ReadWriteOnce
 persistentVolumeReclaimPolicy: Retain
 hostPath:
   path: /vol/data

Apply the PersistentVolume:

kubectl apply -f web-pv.yaml

Step 2: Create the PersistentVolumeClaim

YAML Definition

Create a file named web-pvc.yaml:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
 name: web-pvc
 namespace: production
spec:
 accessModes:
   - ReadWriteOnce
 resources:
   requests:
     storage: 2Gi

Apply the PersistentVolumeClaim:

kubectl apply -f web-pvc.yaml

Verify the PVC is bound to the PV:

kubectl get pvc -n production kubectl get pv

Step 3: Create the Deployment

YAML Definition

Create a file named web-deploy.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
 name: web-deploy
 namespace: production
spec:
 replicas: 1
 selector:
   matchLabels:
     app: web
 template:
   metadata:
     labels:
       app: web
   spec:
     containers:
     - name: web
       image: nginx:1.14.2
       volumeMounts:
       - mountPath: /tmp/web-data
         name: web-storage
     volumes:
     - name: web-storage
       persistentVolumeClaim:
         claimName: web-pvc

Apply the deployment:

kubectl apply -f web-deploy.yaml

Verify that the pod is running and using the volume:

kubectl get pods -n production -o wide kubectl describe pod -n production

 

Alternative: Use Imperative Commands for Faster Deployment (CKA Exam Tip!)

 

Create the PersistentVolume

kubectl create pv web-pv --capacity=2Gi --access-modes=ReadWriteOnce --hostpath=/vol/data -o yaml > web-pv.yaml kubectl apply -f web-pv.yaml

 

Create the PersistentVolumeClaim

kubectl create pvc web-pvc --namespace=production --access-modes=ReadWriteOnce --request=2Gi -o yaml > web-pvc.yaml kubectl apply -f web-pvc.yaml

Create the Deployment

kubectl create deployment web-deploy --image=nginx:1.14.2 --replicas=1 --namespace=production -o yaml > web-deploy.yaml kubectl apply -f web-deploy.yaml