To understand Docker Volume, we first need to understand how Docker file system works. A Docker image is a stack of read-only layers of multiple file systems. When a container is started with the command Docker run, Docker loads the read-only image layer and adds a read-write layer to the top of the image stack. If the running container modifies an existing file, the file will be copied from the read-only layer below the read-write layer to the read-write layer, but the read-only version of the file will still exist, but it will be hidden by the copy of the file in the read-write layer.
When the Docker container is deleted and restarted with the image, previous changes in the read/write layer are lost. In Docker, the combination of the read-only layer and the read-write layer at the top is called Union File System, or UnionFS for short. It uses an important resource management technique called copy-on-write. Copy-on-write, also known as implicit sharing, is a resource management technology that efficiently copies modifiable resources. If you do not modify a duplicate resource, you do not need to create a new resource immediately. The resource can be shared. New resources are created when changes are made. This greatly reduces the cost of copying unmodified resources. In fact, the concept of COW is not unfamiliar to programmers, and it is widely used in various fields, such as ABAP for Internal table copy action, Java string copy implementation and so on. Docker creates containers based on UnionFS.
Let’s look at a practical example.
Use the command line docker run –help to view the help documentation for this command. -h specifies the host name of the container.
Create a new container using the command line:
docker run -it –name jerry-container-test -h CONTAINER -v /data busybox /bin/sh
The name is jerry-container-test, and a volume /data is created with -v
After creation, execute CD /data in the container to access the directory, which is still empty.
Docker ps check container status:
Now I want to know which internal directory is used on the host to implement this volume.
Docker inspect jerry-container-test to check out “volumes”:
/data (); /data ();
/var/lib/docker/volumes/96aa969033ee7e6d7ff607a0a47de5a5866613a422518ed3f86fee6240bae8cc/_data
Now I use the touch command on the host to create a file directly in this directory:
sudo touch /var/lib/docker/volumes/96aa969033ee7e6d7ff607a0a47de5a5866613a422518ed3f86fee6240bae8cc/_data/test.s
Now switch to the container and use ls to see the files created directly on the host using the touch command in the Internal Folder.
For more of Jerry’s original articles, please follow the public account “Wang Zixi “: