Configure a Pod to Use a PersistentVolume for Local directory

  1. Create Persistent Volume
  2. Create Persistent Volume Claim
  3. Create Pod which mounted with Persistent Volume Claim
apiVersion: v1
kind: PersistentVolume
metadata:
  name: hostpath-pv
spec:
  storageClassName: ""
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  claimRef:
    namespace: default
    name: hostpath-pvc
  hostPath:
    path: /tmp/data
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: hostpath-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
apiVersion: v1
kind: Pod
metadata:
  name: hostpath-nginx-pod
  labels:
    app: hostpath-nginx
spec:
  containers:
    - name: hostpath-nginx-container
      image: nginx
      volumeMounts:
        - mountPath: "/tmp"
          name: hostpath-volume-data
      ports:
        - containerPort: 80
          protocol: TCP
  volumes:
    - name: hostpath-volume-data
      persistentVolumeClaim:
        claimName: hostpath-pvc
$ kubectl create -f hostpath-pv.yaml 
persistentvolume/hostpath-pv created

$ kubectl create -f hostpath-pvc.yaml 
persistentvolumeclaim/hostpath-pvc created

$ kubectl create -f hostpath-nginx-pod.yaml 
pod/hostpath-nginx-pod created

// Inside the pod
$ kubectl exec -it hostpath-nginx-pod -- sh
$ touch /tmp/newfile

// Inside of the HostPath location
$ minikube ssh
                         _             _            
$ ls /tmp/data
newfile

When a file is created in the pod, the file also mounted in a local directory.

Leave a Reply

Your email address will not be published.

ANOTE.DEV