Copying data between Docker containers

When running docker there are use-cases when you need to copy files and folders into the container or between containers.

There is a `docker cp` command available since the Docker 1.0 that allows you to copy files and folders out of the container. However, if you need to copy from the host to a container or between containers you’re out of luck now. At least, `docker cp` doesn't support that.

One could create a new image each time or mount a data volume, but it is much faster to copy a bunch of files to the running container.

Docker 1.7.0 should have an extended `docker cp` command to support copying data to containers. Until that, you can use one of the alternative solutions.

In this article, I present you a workaround that relies solely on `docker cp` and `docker exec` to partially fill-in the feature we’re missing.

We consider three file copy scenarios:

from a container’s filesystem to the host path (available, Docker 1.0)

from the host path to a container’s filesystem (upcoming, Docker 1.7)

from one container to the other (upcoming, Docker 1.7)

You can skip the implementation details below and get the source code at the bottom of the article.

Implementation details

CONTAINER:PATH -> HOSTPATH

To copy files or folders from a container to the host we have a native `docker cp` command available since the Docker 1.0.

For example, if we have a container named kickass_yonath and wish to copy /home/data.txt from this container to the host’s current directory, it can be done the following way:

$ docker cp kickass_yonath:/home/data.txt .

HOSTPATH -> CONTAINER:PATH

To copy files from the host to a container one can use the `docker exec` command available since Docker 1.3.0.

If have a test.txt file and wish to copy it to /home/e1/e2 in kickass_yonath container, first of all, we create a directory structure in the container with mkdir:

Source Code

The script `dcp.sh` for copying files and folders between docker containers can be downloaded from the github repo. See the included readme file for the details of usage.

NOTE: This shell script doesn't intend to replace the extended `cp` command in the upcoming Docker 1.7, it just implements some of the functionality we’re missing right now. It is encouraged to use the extended `docker cp` in the upcoming Docker instead of this script.