Using Data Volume Containers with Docker

A Data Volume Container is the perfect way to share some persistent data between containers. Let's see how to create one to share the persistent storage for postgres database.

We will create a new named container with a volume to share. Even if this container doesn’t run an application, it reuses the training/postgres image so that all containers are using layers in common, saving disk space. Start my creating the container,exposing the folder "dbdata":

$ docker create -v /dbdata --name dbdata postgres /bin/true

Now you can use the --volumes-from flag to mount the /dbdata volume in another Docker container.

$ docker run -d --volumes-from dbdata --name data1 postgres

And you can add more:

$ docker run -d --volumes-from dbdata --name data2 postgres

What happens if your postgres image contains already a directory called /dbdata ? Then mounting the volumes from the dbdata container hides the /dbdata files from the postgres image. As a result only the files from the dbdata container are visible.

You can even use multiple --volumes-from parameters to chain together multiple data volumes from several containers. You can also extend the chain by mounting the volume that came from the dbdata container in yet another container via the data1 or data2 containers.

$ docker run -d --name data3 --volumes-from data1 postgres

Advertisement

Cookie Alert