Access a local volumes from Docker Container

There are two types of volumes in Docker. The first one we will learn now are bind mount volumes which use any user-specified directory or file on the host operating system.. You can use Bind volumes when you want to provide to the container some resources which are available on the local, host machine.

In this example we will use the Apache httpd image from within the Docker container but mount a local volume for the http documents. Start by pulling Apache image:

docker pull httpd

 Now let's start is as follows:

docker run -d --name myweb -v /home/frank/htdocs:/usr/local/apache2/htdocs -p 80:80 httpd:latest

In this example you used the -v option and a location map to create the bind mount volume. The map is delimited with a colon. On the left we have included the absolute path of a location on the host file system, and on the right the location where it should be mounted inside the container. (Default /usr/local/apache2/htdocs).

Now check which address has been assigned to the Container. First let's get the Container ID:

[root@localhost htdocs]# docker ps
CONTAINER ID        IMAGE               COMMAND              CREATED             STATUS              PORTS                NAMES
2dc96cdcc1a1        httpd:latest        "httpd-foreground"   8 minutes ago       Up 8 minutes        0.0.0.0:80->80/tcp   myweb

 Now inspect the Container ID IP Address:

[root@localhost htdocs]# docker inspect -f '{{ .NetworkSettings.IPAddress }}' 2dc96cdcc1a1
172.17.0.2

 Great! Now create some example pages on your local host (/home/frank/htdocs) and access it through the browser at http://172.17.0.2

This example however contains a weakness: the volume has been mounted as read-write. By mounting the volume as read-only, you can prevent any process inside the container from modifying the content of the volume. By adding ro to the mount point, you will be able to safely mount your local file system:

docker run -d --name myweb -v /home/frank/htdocs:/usr/local/apache2/htdocs/:ro -p 80:80 httpd:latest

Pro e Cons: Bind Volumes use files in a known location on the host system, and makes it easy for tools and applications on the host system to access the files. The downside is that the user needs to make sure that the directory exists, and that e.g. directory permissions and other security mechanisms on the host system are set up correctly.


Advertisement

Cookie Alert