Data volume containers come in handy when you have data that you want to share between containers. There is another flag we can utilize on the docker run
command. Let’s take a look at the --volumes-from
switch.
What we will be doing is using the -v
switch on one of our Docker containers. Then, our other containers will be using the --volumes-from
switch to mount the data to the containers that they run.
First step, let’s fire up a container that has a data volume we can add to other containers.
For this example, we will be using the busybox
image since it’s very small in size. We are also going to use the --name
switch to give the container a name that can be used later:
$ docker run -it -v /data --name datavolume busybox /bin/sh
We are going to create a volume and mount it in /data
inside our container. We have also named our container datavolume
so that we can leverage in our --volumes-from
switch. While we’re still inside the shell, let’s add some data to the /data
directory. So, when we mount it on the other systems, we know it’s the right one:
$ touch /data/correctvolume
This will create the correctvolume
file inside the /data
directory in the busybox
container we are running.
Now, we need to connect some containers to this /data
directory in the container. This is where the name we gave it will come in handy:
$ docker run -it --volumes-from datavolume busybox /bin/sh
If we now perform ls /data
, we should see the correctvolume
file that we created earlier.
There will come a time when you run into the following error:
$ docker run -it -v /data --name datavolume busybox /bin/bash Error response from daemon: Conflict. The name “data” is already in use by container 82af96592008. You have to delete (or rename) that container to be able to reuse that name.
You can remove the volume if you want, but USE IT CAUTIOUSLY, as once you remove the volume, the data inside that volume will go away with it:
$ docker rm -v data
You can also use this to clean up the volumes that you no longer want on the system. But again, use extreme caution as stated before that once a volume is gone, the data will go with it.