subPath
do for you?I've always been confused as to what purpose subPath
serves. I've come across subPath
whenever a configmap was mounted: it looked like it was used as a way to control which keys in a configmap or secret are projected… but I was never sure.
In this page, I'll try to uncover what exactly is happening when using subPath
and finally get some firm understanding.
We will be using Kind to test things out. Let's create a kind cluster:
We will need the tree
utility too:
Let's consider the following configmap:
And the following pod manifest; pay close attention to volumes
and volumeMounts
:
Now, I'll need to inspect the rootfs of the example container above. I'll use the command podbash
defined as follows:
With podbash
, I can inspect the container's rootfs as well as look at the mountinfo. For example:
It's interesting to look at the mount information to understand the role of subPath
. The output of mountinfo
looks like this:
To make this a little more readable, I've turned this into a table:
Host volume | Pod mount point |
---|---|
/lib/kubelet/pods/bc2bf/volumes/kubernetes.io~configmap/conf/..2024_07_01_14_15_02.3624755718/conf.yaml | /etc/conf.yaml |
Now, let's make the distinction between mountPath
and subPath
:
mountPath
is about the pod mount point.subPath
is about the host volume path.Without subPath
, the outcome would have been very different. Let's remove the subPath
from the manifest:
The host "volume" (a directory, really) looks like this:
The pod mount point looks off:
The problem is that /etc/conf.yaml
is now a directory rather than a file…
That's where subPath
is useful: when you need to mount a single file rather than an entire folder.
More specifically, subPath
allows you to select which path under the host volume path /lib/kubelet/pods/bc2bf/volumes/kubernetes.io~configmap/conf.yaml/
needs to be mounted.
Important learnings:
subPath
isn't found, what's mounted at mountPath
is a host-mounted volume that is made of an empty directory. The subPath
name doesn't matter in this case.subPath
corresponds to a file in the host volume (e.g., it matches a configmap key), that file alone is mounted to mountPath
.subPath
corresponds to a directory in the host-mounted volume (only happens when mounting a PV volume), then mountPath
is a directory that corresponds to the sub- directory subPath
in the host-mounted volume.If your concern is that you want to mount multiple configmap keys to a directory with existing files (such as /etc
), the following will cause /etc
to be replaced by the host-mounted volume:
The subPath
is exactly what you want in this case. You will have to have one volume mount per file, though:
subPath
that doesn't exist in the host's volume?On the host, since baz
doesn't exist in the configmap myconf
, the host volume is an empty directory:
On the host, when foo
exists in the configmap myconf
, it appears as a file in the host volume: