Docker (Volumes)
A volume is a special directory within the file system that is designed for data persistence, is independent of the life cycle of the container, i.e. survives the deletion of a container. When the container is removed, all data in its file system is deleted, while the volumes associated with the container are not deleted. Volumes can be mapped to folders on the physical machine (host machine).
A container can mount one or more volumes when it is created with the “-v” option, which we can pass to the docker “run” command. (Paths specified must be absolute).
sudo docker run -it -v /home/gio/docker_test:/myvolumes/gio ubuntu:16.04 bash
Lunch:
apt-get update
apt-get install vim
After navigating, inside the container, up to the folder “gio”, we write a file with the program “vim”. We need to install these programs because the image I use is without pre-installed programs.
We will create a file and will write within the text.
In /myvolumes/gio we execute:
vim test
When the vim program is opened, press the “ins” key on the keyboard to enter text. Press “Esc” and write :x! to save and exit the program.
The file you just created is present both in the container’s file system in the path /myvolumes/gio and in the host machine’s file system in the path /home/gio/docker_test. The whole is saved in a persistent way.
Share volumes
Containers can share volumes. This allows us, for example, to create a producer-consumer application, where one container generates data and the other one processes it.
--volumes-from option to docker run
The two containers share the same volume (also present on the host machine).
The command:
sudo docker run -it --name=d2 --volumes-from=754f3665932a
The container 754f3665932a container is where we built the volume /myvolumes/gio. With the command above, we have created new container with name “d2" and we have shared the volume of the container 754f3665932a.