5.10 Moving Data Between Docker Containers and the Host

You can use the -v option of docker run to copy volume data between a data volume container and the host. For example, you might want to back up the data so that you can restore it to the same data volume container or to copy it to a different data volume container.

The examples in this section assume that Docker is running two instances of the data volume container image mymod/dvc:v1 that is described in Section 5.9, “Creating and Using Data Volume Containers”. You can use the following commands to start these containers:

# docker run -d --name dvc1 mymod/dvc:v1
# docker run -d --name dvc2 mymod/dvc:v1

To copy the data from a data volume to the host, mount the volume from another container and use the cp command to copy the data to the host, for example:

[root@host ~]# docker run --rm -v /var/tmp:/host:rw oraclelinux:7-slim \
   --volumes-from dvc1 cp -r /var/www/html /host/dvc1_files

The container mounts the host directory /var/tmp read-writable as /host, mounts all the volumes, including /var/www/html, that dvc1 exports, and copies the file hierarchy under /var/www/html to /host/dvc1_files, which corresponds to /var/tmp/dvc1_files on the host.

To copy the backup of dvc1's data from the host to another data volume container dvc2, use a command such as the following:

[root@host ~]# docker run --rm -v /var/tmp:/host:ro --volumes-from dvc2 \
  oraclelinux:7-slim cp -a -T /host/dvc1_files /var/www/html

The container mounts the host directory /var/tmp read-only as /host, mounts the volumes exported by dvc2, and copies the file hierarchy under /host/dvc1_files (/var/tmp/dvc1_files on the host) to /var/www/html, which corresponds to a volume that dvc2 exports.

You could also use a command such as tar to back up and restore the data as a single archive file, for example:

[root@host ~]# docker run --rm -v /var/tmp:/host:rw --volumes-from dvc1 \
  oraclelinux:7-slim tar -cPvf /host/dvc1_files.tar /var/www/html
/var/www/html/
/var/www/html/file1.html
/var/www/html/file2.html
/var/www/html/index.html
[root@host ~]# ls -l /var/tmp/dvc1_files.tar
-rw-r--r--. 1 root root 10240 Aug 31 14:37 /var/tmp/dvc1_files.tar
[root@host ~]# docker run --rm -i -t --name guest -v /var/tmp:/host:ro \
  --volumes-from dvc2 oraclelinux:7-slim /bin/bash
[root@guest ~]# rm /var/www/html/*.html
[root@guest ~]# ls -l /var/www/html/*.html
total 0
[root@guest ~]# tar -xPvf /host/dvc1_files.tar
var/www/html/
var/www/html/file1.html
var/www/html/file2.html
var/www/html/index.html
[root@guest ~]# ls -l /var/www/html
total 12
-rw-r--r--. 1 root root 35 Aug 30 09:02 file1.html
-rw-r--r--. 1 root root 35 Aug 30 09:03 file2.html
-rw-r--r--. 1 root root 35 Aug 30 09:03 index.html
[root@guest ~]# exit
exit
[root@host ~]# 

This example uses a transient, interactive container named guest to extract the contents of the archive to dvc2.