DEV Community

Cover image for Use k8s hostPath volumes in Docker Desktop on WSL2
Nils
Nils

Posted on

Use k8s hostPath volumes in Docker Desktop on WSL2

Kubernetes allows to easily mount volumes based on a path on the node. This can be useful in local development as tools like Docker Desktop make it convenient to spin up a Kubernetes cluster on your local machine.

apiVersion: apps/v1
kind: Deployment
spec:
  ...
  template:
    spec:
      containers:
          image: alpine:latest
          volumeMounts:
            - mountPath: /secrets
              name: secrets-volume
      volumes:
        - name: secrets-volume
          hostPath:
            path: ???
Enter fullscreen mode Exit fullscreen mode

But when you are using Kubernetes with Docker Desktop on WSL2 on a Windows machine, the above can become tricky as many paths will not behave as expected.

After failing to mount regular paths - both inside and outside WSL2, I condensed a long google search into finding that paths under /mnt/wsl are available to be used when referenced as /run/desktop/mnt/host/wsl.

Consider the following example: We want to mount the file secret.env from a local WSL2 folder into a Kubernetes pod. To do so, we first create the file locally:

mkdir /mnt/wsl/secrets
echo "thisissecretdata" > /mnt/wsl/secrets/secret.env
Enter fullscreen mode Exit fullscreen mode

We then mount this via the deployment.yaml:

...
    spec:
      containers:
          image: alpine:latest
          volumeMounts:
            - mountPath: /secrets
              name: secrets-volume
      volumes:
        - name: secrets-volume
          hostPath:
            path: /run/desktop/mnt/host/wsl/secrets
Enter fullscreen mode Exit fullscreen mode

Now inside our pod, we can access the file at /secrets/secret.env and will get the data originally stored in /mnt/wsl/secrets/secret.env.

Top comments (0)