Persistent Volumes with Docker Desktop and Kubernetes
The path to finding the right path
Docker Desktop Kubernetes containers don’t see the same filesystem that WSL Distros do
There’s probably a lot of reasons why the developers haven’t made it more straightforward — virtualizing networking and containerization is already a hard problem to solve — but thatmeans that if you want to mount files in kubernetes that live in WSL2, you may find yourself stumped why your containers can’t seem to find the volumes.
This is because the filesystem your containers see is a different file path than what your linux distro sees. If you create the following directory:
mkdir -p /mnt/wsl/data/postgres
Your docker containers might expect a persistent volume like:
apiVersion: v1
kind: PersistentVolume
metadata:
name: postgres-volume
labels:
type: local
spec:
storageClassName: databases
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/mnt/wsl/data/postgres"
What you might not know unless you found this gem that explains how the docker-desktop WSL integration links the filesystems you might not realize that using the same path in your persistent volume won’t let your containers see anything — they’ll complain about non-existent directories.
Docker Desktop has to service multiple linux distros — so they created a “cross distro mount” that is visible across linux distributions in WSL2. This is located in /mnt/wsl/
— but it has some odd behavior from the docker perspective. Docker doesn’t live in your WSL distribution — it’s injected into it — so volumes in this shared cross distro mount don’t show up with the same file path from the docker perspective as a normal host mounted directory — /mnt/wsl
from the docker host perspective is actually /run/desktop/mnt/host/wsl
.
How do I get a kubernetes pod with a persistent volume to see the right location?
You have to substitute /mnt/wsl
with /run/desktop/mnt/host/wsl
so that the docker service that kubernetes is running can see the data. If my persistent volume local directory is in WSL under the path
/mnt/wsl/data/postgres
Then the correct persistent volume path will be
apiVersion: v1
kind: PersistentVolume
metadata:
name: postgres-volume
labels:
type: local
spec:
storageClassName: databases
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/run/desktop/mnt/host/wsl/data/postgres"
With that adjustment any data from the running container will be updated in my WSL distro folder under /mnt/wsl/data/postgres
with all the usual convenience of docker local volumes that make iteration and dropping files into a container easy.