Kubernetes Hostpath Volume Example
A Kubernetes hostPath volume mounts a file or directory from the host node’s filesystem into your Pod. Kubernetes supports hostPath for development and testing on a single-node cluster. In a production cluster we would not use Kubernetes hostPath. Even if the pod dies, the data is persisted in the host machine. In order for HostPath to work, you will need to run a single node cluster. Kubernetes does not support host path for multimode cluster. Since There is no guarantee that your pod will end up on the correct node where the HostPath resides.
Some uses for a kubernetes hostPath are:
- running a container that needs access to Docker internals; use a hostPath of /var/lib/docker
- running cAdvisor in a container; use a hostPath of /dev/cgroups
How to use Hostpath in Multinode cluster
When the host path is going to created in the pod. Kubernetes scheduler will check on that node, is that host path is existed or not. But most of the times host path is not available in all nodes since it is a multinode cluster. So the kubernetes will create an empty directory on the node. And it will mount this empty directory into container. So if you want to mount any node directory into container use nodeselector. Using node selector we can use hostpath in multinode cluster otherwise you empty directory will be mounted.
Kubernetes Hostpath volume example
cat mydep.yml
apiVersion: apps/v1beta1 kind: Deployment metadata: labels: run: myweb name: myweb spec: replicas: 1 selector: matchLabels: run: myweb template: metadata: labels: run: myweb spec: containers: - image: centos/httpd name: myweb volumeMounts: - mountPath: /devops name: myvolume volumes: - name: myvolume hostPath: path: /root/python type: Directory
kubectl apply -f mydep.yml
once you created the deployment you can see the pod will be created in your node.
master $ kubectl get pods NAME READY STATUS RESTARTS AGE web-6dccd4b9d8-wpptn 1/1 Running 0 16m
enter into container using kubectl exec command.
master $ kubectl exec -it web-6dccd4b9d8-wpptn bash [root@web-6dccd4b9d8-wpptn /]#
verify is the devops directroy created or not
[root@web-6dccd4b9d8-wpptn /]# ls anaconda-post.log boot etc home lib64 mnt proc run sbin sys usr devops bin dev lib media opt root run-httpd.sh srv tmp var
You can see devops directory is created. So whatever the data inside /root/python directory in node, the same data mounted into the container devops directory.
if the container writes any data into devops directory that data will be shared or available in node /root/python directory. If you added any new data in node /root/python directory the same data you can see in container devops directory. In this way the volume will be shared between node and container in vice versa.
- Kubernetes Hostpath volume example
- Kubernetes Hostpath volume example
- Hostpath volume Kubernetes example
- Kubernetes volume Hostpath