Docker data volumes and sharing data

Docker containers are temporary.

You can experiment this by starting a basic ubuntu image and create a test file or dir. The soon you exit the container all your changes will disappear.

Let’s try to bring that container up again:

Thankfully Docker provides the solution to keep data persistent.

Docker Data Volumes

Docker data volumes are used when:

  1. You want to persist data, even through container restarts
  2. You want to share data between the host filesystem and the Docker container
  3. You want to share data with other Docker containers.

Data persist

There’s no way to directly create a “data volume” in Docker, so instead we create a data volume container with a volume attached to it. For any other containers that you then want to connect to this data volume container, use the Docker’s –volumes-from option to grab the volume from this container and apply them to the current container.

Le’s create a data volume container to store our volume:

This created a container named datacontainer based on ubuntu image and in the directory /data.

If we reiterate our initial test with –volumes-from flag, anything we write to /data directory into current container will be saved to the /data volume of our datacontainer.

Now rerun the container and check if /data/my_file is persisted.

You can also create as many data volume containers as you’d like but you are restricted to choose the mount inside the container (/data in our example).

Sharing data between containers – shared volumes

There is the need to share data between host and container itself. Docker gives you the option to run a container and override one of its directories with the contents of a directory on the host system.

Let’s imagine you’re running your application and you want to keep the logs out of container.

We set up a volume that links the /var/log/nginx directory from the nginx container to ~/nginxlogs on our host.

If you make any changes to the ~/nginxlogs folder, you’ll be able to see them from inside the Docker container in real-time as well.

Additional links: