Docker Volumes can be created and attached in the same command that creates a container, or they can be created independently of any containers and attached later. In this article, we’ll look at four different ways to share data between containers.
Step 1 — Creating an Independent Volume
Introduced in Docker’s 1.9 release, the docker volume create command allows you to create a volume without relating it to any particular container. We’ll use this command to add a volume named DataVolume1:
docker volume create --name DataVolume1
The name is displayed, indicating that the command was successful:
Output
DataVolume1
To make use of the volume, we’ll create a new container from the Ubuntu image, using the --rm flag to automatically delete it when we exit. We’ll also use -v to mount the new volume. -v requires the name of the volume, a colon, then the absolute path to where the volume should appear inside the container. If the directories in the path don’t exist as part of the image, they’ll be created when the command runs. If they do exist, the mounted volume will hide the existing content:
docker run -ti --rm -v DataVolume1:/datavolume1 ubuntu
While in the container, let’s write some data to the volume:
echo “Example1” > /datavolume1/Example1.txt
docker volume inspect DataVolume1
Output
[
{
“CreatedAt”: “2018-07-11T16:57:54Z”,
“Driver”: “local”,
“Labels”: {},
“Mountpoint”: “/var/lib/docker/volumes/DataVolume1/_data”,
“Name”: “DataVolume1”,
“Options”: {},
“Scope”: “local”
}
]
Next, start a new container and attach DataVolume1:
docker run --rm -ti -v DataVolume1:/datavolume1 ubuntu
Verify the contents:
cat /datavolume1/Example1.txt
Output
Example1
===========================
Step 2 — Creating a Volume that Persists when the Container is Removed
docker run -ti --name=Container2 -v DataVolume2:/datavolume2 ubuntu
When we restart the container, the volume will mount automatically:
docker start -ai Container2
Let’s verify that the volume has indeed mounted and our data is still in place:
cat /datavolume2/Example2.txt
Output
Example2
Step 3 — Creating a Volume from an Existing Directory with Data
As an example, we’ll create a container and add the data volume at /var, a directory which contains data in the base image:
docker run -ti --rm -v DataVolume3:/var ubuntu
Step 4 — Sharing Data Between Multiple Docker Containers
Create Container4 and DataVolume4
Use docker run to create a new container named Container4 with a data volume attached:
docker run -ti --name=Container4 -v DataVolume4:/datavolume4 ubuntu
Create Container5 and Mount Volumes from Container4
We’re going to create Container5, and mount the volumes from Container4:
docker run -ti --name=Container5 --volumes-from Container4 ubuntu
View Changes Made in Container5
Let’s check for the changes that were written to the data volume by Container5 by restarting Container4:
docker start -ai Container4