DEV Community

Cover image for Mount Docker volume locally
Adam K Dean
Adam K Dean

Posted on • Updated on

Mount Docker volume locally

Edit 25 Oct 2021: Seems this no longer works. So much for a workaround.

Here is something that's cool.

You can have a docker volume, docker volume create example, and you can mount this volume to a container, docker run -v example:/path image. You can also mount local directories to containers, docker run -v $(pwd)/local:/path image. But something you can't do, is mount a local directory to volume.

Scenario: you have a volume, you have a container using that volume, and you have some software that needs to access that volume data locally, outside of docker.

🚫docker run -v $(pwd)/local:example image isn't going to work.

Nor can you mount two things to the same place.

🚫docker run -v example:/example -v $(pwd)/local:/example image isn't going to work either.

The solution is to use intermediate symlinked container.

I call this solution the map volume.

#
# map volume
#
FROM busybox
RUN mkdir /volume
RUN ln -s /local /volume
CMD tail -f /dev/null
Enter fullscreen mode Exit fullscreen mode

In this dockerfile you can see that we create a directory (later to be used as a mount point), and then we create a symlink directory pointing to the same place.

$ docker build -t mapvolume .
$ docker volume create my_precious_data
$ docker run -d -v my_precious_data:/volume -v $(pwd)/my_precious_data:/local mapvolume
Enter fullscreen mode Exit fullscreen mode

We create a volume my_precious_data, then we run the mapvolume, first mounting the volume my_precious_data to the container path /volume, and then mounting the local directory $(pwd)/my_precious_data to the container path /local which as we saw, is actually /volume.

Now you have mounted a docker volume to your local filesystem.

Update: I realised today that the original dockerfile wouldn't stay alive. I therefore changed the CMD to CMD tail -f /dev/null to keep the container alive. Thanks to bigdatums.net for that snippet.

Top comments (2)

Collapse
 
arki7n profile image
Akhilesh Yadav

Seems, doesnt work an longer.

Collapse
 
adamkdean profile image
Adam K Dean

Just noticed this. Blimey. No idea what we can do now :/