How To Mount Your Current Working Directory To Your Docker Container In Windows

Docker is super handy for anyone wanting to write software in a Linux environment while still running a Windows computer. One of the biggest hurdles I’ve learnt using Docker with Windows is knowing how to mount my working directory to any arbitrary docker container. Instead of anyone else going through the same pain I have, I decided to quickly write up an article to help new Docker users how to do this.

Docker — Super handy for Linux users on Windows computers

You’d expect that there would be an easy answer using either the ADD or VOLUME command to your Dockerfile. The problem with using this method is that you have to rebuild your image every time the parent folder changes. This could be a change because of renaming of your project, or a change from simply working on a new project. This is not ideal. There is instead another way.

The Trick

Instead I’ve found the easiest method is to use the --volume flag when running the docker run command. With this command, you can attach the local directory to your docker container at runtime instead of during the build process.

The --volume command takes a single parameter formatted like so:

<host directory>:<target directory>

where the host directory is the directory you wish to mount and the target directory is the location in the container where this directory is accessible.

There is an additional part to this trick however — you can not use native Windows path formats for your host directory. Instead, you need to convert your path into a quasi-Linux format. The formatting rules (which I’ve noticed so far) are as so:

  1. You must replace any drives of the format C:\ with the new format //c/ , obviously replacing the C and c with the drive that is to be used.
  2. Any back-slash is to be replaced with a forward-slash.

I’ve read online that, in theory, it is possible to remove all hard-coded values using the $(pwd) in PowerShell yet I’m unable to get that to work successfully. Writing my path once every few hours is okay enough for me.

Example

It’s easier to understand the trick when put into practice. Here I’ve created a scenario where I would like to mount my current working directory (C:\Users\kale\my_project) into the ubuntu:latest image at the /home/project location in the container. We would do that as so:

docker run -it --volume //c/Users/kale/my_project:/home/project ubuntu:latest

This should start up your container and attach your working directory. Now any changes you make locally (i.e. in your Windows machine) will be reflected in your docker container!

As always, thanks for reading. If you liked the article please leave a few claps so other users can find it more easily. Also feel free to give me a follow to stay up to date with any articles I publish.

Data Scientist, Self-Taught Developer, All-Round Nerd.

Data Scientist, Self-Taught Developer, All-Round Nerd.