User Tools

Site Tools


docker:share_data_between_docker_containers

This is an old revision of the document!


Docker - Share data between docker containers

Docker Volumes can be created and attached in the same command that creates a container, or they can be created independent of any containers and then attached later. There are a number of different ways to share data between containers.

Creating an Independent Volume

Docker's 1.9 onwards allows a volume to be created without it relating to any particular container:

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 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

Write some data to the volume:

echo "Example1" > /datavolume1/Example1.txt

Because we used the –rm flag, the container will be automatically deleted when we exit. The volume, however, will still be accessible.

exit

Verify the volume is present on the system with docker volume inspect:

docker volume inspect DataVolume1

Result

Output
[
    {
        "Name": "DataVolume1",
        "Driver": "local",
        "Mountpoint": "/var/lib/docker/volumes/datavolume1/_data",
        "Labels": null,
        "Scope": "local"
    }
]

WARNING: The data on the host can also be accessed at the path listed as the Mountpoint. Avoid altering this as it can cause data corruption if applications or containers are unaware of changes.

Start a new container and attach DataVolume1:

docker run --rm -ti -v DataVolume1:/datavolume1 ubuntu
cat /datavolume1/Example1.txt

Displays:

Output
Example1

Exit the container.

exit

In this example, we created a volume, attached it to a container, and verified its persistence.

docker/share_data_between_docker_containers.1487777231.txt.gz · Last modified: 2020/07/15 09:30 (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki