Volumes from Docker Image

Docker Image with Volume specified in Dockerfile

In this lab we look at

  1. How to add a file as a volume using Dockerfile format.
  2. Create an Image from the Dockerfile
  3. Use the Image to create a container and check if the file exists.

Create the Dockerfile

Create a Dockerfile as shown below in a directory. Make sure file1 exists in the same directory. We are gong to mount file1 as /ubuntu1/file and mount /ubuntu1 as a VOLUME.

FROM ubuntu
ADD file1 /ubuntu1/file
VOLUME /ubuntu1
CMD /bin/sh

Create an Image from the Dockerfile

Execute the command below to build the image test/volume-one-dockerfile

docker build -t test/volume-one-dockerfile .

Create a Docker container

Create a container from the image test/volume-one-dockerfile

docker run -it test/volume-one-dockerfile

This command above will launch the bash shell of the container. Check if the volume /ubuntu1 is mounted

# ls
bin  boot  dev      etc  home  lib  .. sbin  srv  sys  tmp  ubuntu1  usr  var
# ls /ubuntu1

Docker Container with volume from Command Line and Image

In this section you will learn how to use command line to mount a host directory into a container created from an image

Create a Local directory

Create a local directory ubuntu2 and two files file1 and file2 in that directory.

$sudo mkdir -p /ubuntu2
[sudo] password for ubuntu:
$ sudo touch /ubuntu2/file1
$ sudo touch /ubuntu2/file2

Create a Container with a Volume ubuntu2

Create a container from the image :code:test/volume-one-dockerfile by specifying the directory to be mounted on the command line with a flag -v.

$ docker run -it -v /ubuntu2:/ubuntu2 test/volume-one-dockerfile

Check that the directory ubuntu2 got mounted in the docker container. Run ls in the container shell.

# ls
bin  boot  dev      etc  home  lib sys  tmp  ubuntu1  ubuntu2       usr  var
# ls ubuntu2
file1  file2

As you can see above both ubuntu1 and ubuntu2 got mounted as volumes.


Container with ReadOnly Volume

Specify the :ro as shown below to make the volume readonly.

$ docker run -it -v /ubuntu2:/ubuntu2:ro test/volume-one-dockerfile

Try creating a new file in that volume from the bash shell of the container.

# touch /ubuntu2/file3
touch: cannot touch '/ubuntu2/file3': Read-only file system