Docker: Copying files from Docker container to host Docker: Copying files from Docker container to host docker docker

Docker: Copying files from Docker container to host


In order to copy a file from a container to the host, you can use the command

docker cp <containerId>:/file/path/within/container /host/path/target

Here's an example:

$ sudo docker cp goofy_roentgen:/out_read.jpg .

Here goofy_roentgen is the container name I got from the following command:

$ sudo docker psCONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                                            NAMES1b4ad9311e93        bamos/openface      "/bin/bash"         33 minutes ago      Up 33 minutes       0.0.0.0:8000->8000/tcp, 0.0.0.0:9000->9000/tcp   goofy_roentgen

You can also use (part of) the Container ID. The following command is equivalent to the first

$ sudo docker cp 1b4a:/out_read.jpg .


You do not need to use docker run.

You can do it with docker create.

From the docs:

The docker create command creates a writeable container layer over the specified image and prepares it for running the specified command. The container ID is then printed to STDOUT. This is similar to docker run -d except the container is never started.

So, you can do:

docker create -ti --name dummy IMAGE_NAME bashdocker cp dummy:/path/to/file /dest/to/filedocker rm -f dummy

Here, you never start the container. That looked beneficial to me.


Mount a "volume" and copy the artifacts into there:

mkdir artifactsdocker run -i -v ${PWD}/artifacts:/artifacts ubuntu:14.04 sh << COMMANDS# ... build software here ...cp <artifact> /artifacts# ... copy more artifacts into `/artifacts` ...COMMANDS

Then when the build finishes and the container is no longer running, it has already copied the artifacts from the build into the artifacts directory on the host.

Edit

Caveat: When you do this, you may run into problems with the user id of the docker user matching the user id of the current running user. That is, the files in /artifacts will be shown as owned by the user with the UID of the user used inside the docker container. A way around this may be to use the calling user's UID:

docker run -i -v ${PWD}:/working_dir -w /working_dir -u $(id -u) \    ubuntu:14.04 sh << COMMANDS# Since $(id -u) owns /working_dir, you should be okay running commands here# and having them work. Then copy stuff into /working_dir/artifacts .COMMANDS