MicroK8s - Mount host directory into pods

Why would I need it?

As I mainly want to use Kubernetes to orchestrate my containers, I don’t use multiple nodes. I consider that paying for an external storage solution while I have enough disk space on the host machine is wasting money. I host my Kubernetes cluster on a Vultr VPS.

Note that I could have done it with Docker compose to, but I prefer K8s. Using K8s also allows me to quickly change my cluster to a multi-node cluster if I decide to. Also, managing multiple projects on the same cluster with namespaces and multiple yaml files is easier.

Let’s do it

The official documentation is available here.

Here is a basic deployment file with the HostPath volume.

deployment.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
kind: Deployment
metadata:
name: hello-deployment
spec:
selector:
matchLabels:
app: hello
replicas: 1 # tells deployment to run 2 pods matching the template
template:
metadata:
labels:
app: hello
spec:
containers:
- name: hello
image: nginxdemos/hello:plain-text
ports:
- containerPort: 80

# THE VOLUME CONFIG IS BELOW --------------------------------------
volumeMounts:
- mountPath: /yaml # Path of the volume in the container
name: yaml-volume

volumes:
- name: yaml-volume
hostPath:
path: /root/yaml # Path of the directory on the Host (node)
type: Directory # DirectoryOrCreate, FileOrCreate

Conclusion

It’s fairly esay to mount a volume from the Host. However, this solution is generally a bad idea for multi-nodes clusters, the Pods can be scheduled to a different node and no longer have access to the directory/file. Prefer using the PVCs for this use cases.