Aktualisiert: Jan 22
There are more than 20 volume types Kubernetes supports: https://kubernetes.io/docs/concepts/storage/volumes/
In this blog I will describe different usages of EmptyDir and HostPath volume types.
Each of these volume has its own use case and should be used only in those specific cases. Following is the explanation of each volume type and its use case examples:
An emptyDir volume is first created when a Pod is assigned to a Node, and exists as long as that Pod is running on that node.
As the name says, it is initially empty. All Containers in the same Pod can read and write in the same emptyDir volume.
When a Pod is restarted or removed, the data in the emptyDir is lost forever.
Some use cases for an emptyDir are:
- scratch space, for a sort algorithm for example
- when a long computation needs to be done in memory
- as a cache
Example Config File with a pod that uses emptyDir:
- image: my-app-image
- mountPath: /cache
- name: cache-volume
Note: emptyDir volume should NOT be used for persisting data (database, application data, etc)
A hostPath volume mounts a file or directory from the node's filesystem into the Pod. You can specify whether the file/directory must already exist on the node or should be created on pod startup. You can do it using a type attribute in the config file:
- image: my-app-image
- mountPath: /test-pd
- name: test-volume
path: /data #directory on host
type: Directory #optional
type: Directory defines that the directory must already exist on the host, so you will have to create it there manually first, before using the hostpath.
Other values for type are DirectoryOrCreate, File, FileOrCreate. Where *OrCreate it will be created dynamically if it doesn't already exist on the host.
NOTE: This is not something that most Pods will need, but it offers a powerful escape hatch for some applications.
Some uses for a 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 /sys
Disadvantages of using this volume type:
- Pods created from the same pod template may behave differently on different nodes because of different hostPath file/dir contents on those nodes
- Files or directories created with HostPath on the host are only writable by root. Which means, you either need to run your container process as root or modify the file permissions on the host to be writable by non-root user, which may lead to security issues
- You should NOT use hostPath volume type for StatefulSets