Sunday, 15 April 2018

Sharing Host Directory/Folder with the Docker Container.

In this blog, we are going to learn, how we can mount a existing host folder/directory to a docker container.

Imagine a scenario, where you need to share local files with the docker container. And whenever you modify the files or folder on your host machine i.e outside a container, you need that to be updated in the container also.

This is possible by mounting a host directory with the docker container. Let's checkout the steps for it.

Here in the example, i am using boot2docker VM. So, the host is here boot2docker VM, not our machine, on which it is running. But as boot2docker is a linux VM and running over virtual box, we have the facility of having some folders from the machine mounted over the VM as a host folder.

We can check it, by going to the Oracle Virtual Box -> boot2docker VM -> Settings -> Shared Folders. And here you can see, c/users is already mounted there.

For mounting the host folders, other than c/users, we need to first share it with the VM, then only we can mount it with the container. For this session we will use the already shared folder.

Let's start mounting the host folder:

1. lets first create a folder, under c:/users directory for hosting our code files. I have created a folder name "terraform" under c://users and which consist of some javascript and json files.

2. Now, lets mount the terraform folder into the container at /home/app/config path.
Command :  docker run -v "hostfolder:folderInContainer" imageName

             docker run -it -v "/c/Users/terraform:/home/app/config" terraform /bin/ash

here i am mounting, the terraform host folder at the /home/app/config directory in the container. So, all the contents of terraform directory will be listed under the config folder in the container.

2. let's check, whether our files/content exist into the config folder or not, just "cd" to the config folder and execute the "ls" list command to list down the files.

As we can see, in the above screenshot, couple of json and java-script files listed there.

The good thing about this, whenever we do any changes to the host folder outside of the container, they are automatically sync/reflected in the container. Try yourself by adding couple of files and folder into the host folder and then just try listing the files into the container. You will be amazed to see, that changes are reflected there also.

Thanks for reading this blog.