When the container is removed, its data also gets destroyed and the data where the container writes is tightly coupled with the host machine which makes it really hard to move the data. It makes sense when you have an application that is stateless but for apps where you want to persist the data of the application beyond the life cycle of the container it does not help. Thankfully Docker gives us the option to use volumes that do not get impacted with the lifecycle of the container and persist the application data outside of the container's filesystem, using volumes or a bind mount. Docker volumes are special directories created and managed by Docker. Now let's jump to the volume creation and mapping it to containers.
To create a volume use the below command
docker volume create datavol
Now let us create a container (in interactive mode) and attach it to the datavol volume.
docker container run -it --rm -v datavol:/data alpine
And create a file inside the data directory, refer to the below image.
The moment we exited the terminal of the container, the container is removed. Now let's create another container and attach the same data volume, and check if the file demo.txt
is present in /data
directory.
As per the image above, the file demo.txt
and its content is persisted in the directory /data
The Docker volume can be removed, to remove docker volume rm datavol
Docker allows us to attach the same volume to many containers, so this way we can share data among many containers.
Sharing data between the Host and Container
Above we shared the data among containers and persisted in it, what about sharing data between the Host and the Container. Docker lets us achieve this as well.
Launch a container by mounting the $HOME/data_share
directory and then print the content of the demo.txt
.
echo "data sharing demo" > ./data_share/demo.txt
docker container run --rm -v ./data_share:/data ubuntu cat /data/demo.txt
Here the key is -v <host path>:<container path>
option.
In a similar fashion, we can mount a file to a container, docker container run --rm -v $(HOME)/data_share/demo.txt:/demo.txt ubuntu cat /demo.txt