5.8 Accessing External Files from Docker Containers

You can use the -v option with docker run to make a file or file system available inside a container. The following example demonstrates how to make web pages on the host available to an HTTP server running in a container.

Create the file /var/www/html/index.html on the host and run an HTTP server container that mounts this file:

[root@host ~]# echo "This text was created in a file on the host" > /var/www/html/index.html
[root@host ~]# docker run -d --name newguest3 -P \
  -v /var/www/html/index.html:/var/www/html/index.html:ro mymod/httpd:v2
1197c308cdbae64daaa5422016108be76a085286281e5264e193f08a4cebea20

The :ro modifier specifies that a container mounts a file or file system read-only. To mount a file or file system read-writable, specify the :rw modifier instead or omit the modifier altogether.

Check that the HTTP server is not running on the host:

[root@host ~]# curl http://localhost
curl: (7) couldn't connect to host
[root@host ~]# service httpd status
httpd is stopped

Even though an HTTP server is not running directly on the host, you can display the new web page served by the newguest3 container:

[root@host ~]# docker inspect --format='{{ .NetworkSettings.Ports }}' newguest3
map[80/tcp:[map[HostIp:0.0.0.0 HostPort:49153]]]
[root@host ~]# curl http://localhost:49153
This text was created in a file on the host

Any changes that you make to the /var/www/html/index.html file on the host are reflected in the mounted file in the container:

[root@host ~]# echo "Change the file on the host" > /var/www/html/index.html 
[root@host ~]# curl http://localhost:49153
Change the file on the host

Even if you delete the file on the host, it is still visible in the container:

[root@host ~]# rm /var/www/html/index.html 
rm: remove regular file `/var/www/html/index.html'? y
[root@host ~]# ls -l /var/www/html/index.html
ls: cannot access /var/www/html/index.html: No such file or directory
[root@host ~]# curl http://localhost:49153
Change the file on the host

It is not possible to use a Dockerfile to define how to mount a file or file system from a host. Docker applications are intended to be portable and it is unlikely that a file or file system that exists on the original host would be available on another system. If you want external file data to be portable, you can encapsulate it in a data volume container. See Section 5.9, “Creating and Using Data Volume Containers”.