What is hostPath volume in Kubernetes: Explanation and Example
hostPath volume in Kubernetes mounts a file or directory from the node's filesystem into a pod. It allows containers to access files on the host machine directly, useful for sharing data or accessing host resources.How It Works
A hostPath volume connects a folder or file from the physical machine (node) where your Kubernetes pod runs to the pod itself. Imagine it like sharing a folder from your computer to a guest in your house, so they can use or save files directly on your computer.
When a pod starts, Kubernetes mounts the specified path from the node into the pod's container at the location you choose. This means the container can read or write files as if they were inside the pod, but the data actually lives on the node's disk.
This is different from other volumes that store data inside Kubernetes or cloud storage. hostPath is simple and fast but ties your pod to the node, so it’s less flexible for scaling or moving pods.
Example
This example shows a pod that mounts the host's /data directory into the container at /mnt/data. The container can then access files on the node's /data folder.
apiVersion: v1
kind: Pod
metadata:
name: hostpath-example
spec:
containers:
- name: app
image: busybox
command: ["sleep", "3600"]
volumeMounts:
- name: host-volume
mountPath: /mnt/data
volumes:
- name: host-volume
hostPath:
path: /data
type: DirectoryOrCreateWhen to Use
Use hostPath volumes when you need fast access to files on the node itself, such as:
- Sharing logs or data between pods and the host for debugging.
- Accessing special hardware or device files on the node.
- Using local storage for temporary data that does not need to move with the pod.
However, avoid hostPath for critical data or in multi-node clusters where pods may move, because the data stays on one node and is not shared automatically.
Key Points
- hostPath mounts a node's file or directory into a pod.
- It ties the pod to a specific node, limiting portability.
- Good for accessing host files, devices, or local storage.
- Not suitable for shared or persistent storage across nodes.