Mounting a volume
Once we have created a named volume, we can mount it into a container. For this, we can use the -v parameter in the docker container run command:
$ docker container run --name test -it \
-v my-data:/data alpine /bin/sh
The preceding command mounts the my-data volume to the /data folder inside the container. Inside the container, we can now create files in the /data folder and then exit:
# / cd /data # / echo "Some data" > data.txt # / echo "Some more data" > data2.txt # / exit
If we navigate to the host folder that contains the volume data and list its content, we should see the two files we just created inside the container:
$ cd /mnt/sda1/var/lib/docker/volumes/my-data/_data
$ ls -l
total 8
-rw-r--r-- 1 root root 10 Jan 28 22:23 data.txt
-rw-r--r-- 1 root root 15 Jan 28 22:23 data2.txt
We can even try to output the content of say, the second file:
$ cat data2.txt
Let's try to create a file in this folder from the host and then use the volume with another container:
$ echo "This file we create on the host" > host-data.txt
Now, let's delete the test container and run another one based on CentOS. This time we are even mounting our volume to a different container folder, /app/data:
$ docker container rm test
$ docker container run --name test2 -it \
-v my-data:/app/data \
Centos:7 /bin/bash
Once inside the CentOS container, we can navigate to the folder /app/data where we have mounted the volume to and list its content:
# / cd /app/data # / ls -l
As expected, we should see these three files:
-rw-r--r-- 1 root root 10 Jan 28 22:23 data.txt
-rw-r--r-- 1 root root 15 Jan 28 22:23 data2.txt
-rw-r--r-- 1 root root 32 Jan 28 22:31 host-data.txt
This is the definitive proof that data in a Docker volume persists beyond the lifetime of a container, and also that volumes can be reused by other, even different containers from the one that used it first.
It is important to note that the folder inside the container to which we mount a Docker volume is excluded from the union filesystem. That is, each change inside this folder and any of its subfolders will not be part of the container layer, but persisted in the backing storage provided by the volume driver. This fact is really important since the container layer is deleted when the corresponding container is stopped and removed from the system.