[k8s] How to mount local directory (persistent volume) to Kubernetes pods of Docker Desktop for Mac?

Julien Chen
2 min readDec 31, 2021

I have to mount local directory to my local Kubernetes pods, when I was doing some researches. I tried to mount hostPath (the default StorageClass created by Docker Desktop) like below:

  1. Check and add the directories you want to share into your Docker Desktop preferences.

2. Mount volume to your deployment

apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 1
minReadySeconds: 10
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: myapp:latest
...
volumeMounts:
- name: my-volume
mountPath: /data
volumes:
- name: my-volume
hostPath:
path: /tmp
type: DirectoryOrCreate

...

Note the hostPath.path should be exactly the same with the File sharing path. After you apply all of them, you can go into your pods. Create and modify some files. You will see those files in your local folder.

If you want to practice PersistentVolume, PersistentVolumeReclaim & StorageClass. Refer to this discussion. You can do things like this:

  1. Add the shared folder into Docker Desktop preferences.

2. Apply PersistentVolume & PersistentVolumeClaim like this:

#
# PersistentVolume
#
apiVersion: v1
kind: PersistentVolume
metadata:
name: my-persistent-volume
labels:
type: local
spec:
storageClassName: hostpath
capacity:
storage: 256Mi
accessModes:
- ReadWriteMany
hostPath:
path: /tmp

persistentVolumeReclaimPolicy: Retain
---#
# PersistentVolumeClaim
#
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-persistent-volume-claim
spec:
storageClassName: hostpath
accessModes:
- ReadWriteMany
resources:
requests:
storage: 256Mi

P.S. I tried to set storageClassName to be “manual” like what they did in the discussion, but I encountered pod has unbound immediate persistentvolumeclaims” error.

You can use the default StorageClass hostpath like above. Or create your own StorageClass like below, but don’t forget to change the storageClassName of PersistentVolume & PersistentVolumeClaim.

apiVersion: v1
kind: StorageClass
apiVersion: storage.k8s.io/v1beta1
metadata:
name: my-storage-class
provisioner: docker.io/hostpath

3. Mount the persistentVolumeClaim you just created to your deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 1
minReadySeconds: 10
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: myapp:latest
...
volumeMounts:
- name: my-volume
mountPath: /data
volumes:
- name: my-volume
persistentVolumeClaim:
claimName: my-persistent-volume-claim

...

After you apply all of them, you can go into your pods. Create and modify some files. You will see those files in your local folder.

--

--