In this tutorial, How to Share Data Between Docker Containers. Now, let go Docker Containers Share Data.
I will deploy 2 containers using docker to share data between containers.
Docker containers can share data using various mechanisms provided by Docker. Here are a few ways to share data between Docker containers.
- Host OS: Ubuntu 21.04
- Installed Docker
Create a Volume for Docker containers share data
We will create a Volume to save our data as command below:
docker volume create --name persistent-data-devops
The volume is created in the /var/lib/docker/volumes directory.
vagrant@devopsroles:~$ sudo ls /var/lib/docker/volumes/persistent-data-devops/_data/test.txt /var/lib/docker/volumes/persistent-data-devops/_data/test.txt
For example, We will deploy the first container which will use the persistent volume.
docker run -it --name=container1 -v persistent-data-devops:/data ubuntu:latest
- The container named: container1
- mount the persistent-data-devops volume into the /data directory within the new container
Login new container and create a new file
echo "Hello, www.devopsroles.com" >> /data/test.txt
We’ll now deploy a second container as command below
docker run -it --name=container2 -v persistent-data-devops:/data ubuntu:latest
Login second container and display content
Edit /data/test.txt file. I use the vim command line.
Add the following at the bottom of the file:
This data share between containers 1 and 2
The output terminal as below
vagrant@devopsroles:~$ docker run -it --name=container2 -v persistent-data-devops:/data ubuntu:latest root@ed16b6be95f8:/# cat /data/test.txt Hello, www.devopsroles.com root@ed16b6be95f8:/# vim /data/test.txt root@ed16b6be95f8:/# cat /data/test.txt Hello, www.devopsroles.com This data share between containers 1 and 2
Exit the running container with the exit command. You can stop and remove them with the commands:
docker stop ID docker rm ID
After stopping and removing docker container1, we will deploy again, But data will remain data.
You have to Docker Containers Share Data. These are some of the common methods to share data between Docker containers. Choose the one that best suits your requirements based on the nature of the data and the use case you have in mind. I hope will this your helpful. Thank you for reading the DevopsRoles page!