Copy files to or from a Docker container

Before you begin

In this tutorial, we’ll learn how to copy files from your host to a Docker container and the other way around. A GNU Linux machine/Mac OS X and Docker will be required to follow this tutorial.

This post is all about copying files to containers once they are already running. If you need to copy files when you’re building new Docker images we have another post called “Docker ADD vs COPY commands””.

Create files to test

The command below create files to do the test:

$ touch .0 1 2
$ mkdir foo
$ touch foo/3 foo/4 foo/5
$ tree -a
>
.
├── .0
├── 1
├── 2
└── foo
    ├── 3
    ├── 4
    └── 5

Docker cp

Copy file from host into a Docker container

You can use the following commands to copy files from your host to a Docker container. Docker cp examples:

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

$ docker cp 1 container_name:/tmp/
$ docker exec -it container_name bash -c 'tree -a /tmp'
>
/tmp
└── 1

0 directories, 1 file

Copy files/directories from host into a Docker container

You can use the following commands to copy files and directories from your host into a Docker container. Docker cp examples:

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

$ docker cp . container_name:/tmp/
$ docker exec -it container_name bash -c 'tree -a /tmp/'
>
/tmp/
├── .0
├── 1
├── 2
└── foo
    ├── 3
    ├── 4
    └── 5

1 directory, 6 files

Copy files from Docker container to your host

Finally, you can use the docker cp command to copy files from Docker to your host. Docker cp examples:

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

$ docker cp container_name:/tmp/. .
$ tree -a
>
.
├── .0
├── 1
├── 2
└── foo
    ├── 3
    ├── 4
    └── 5

1 directory, 6 files

Also is possible to use cat to copy a file from docker redirecting output to a file in your host.

docker exec -it <container_id> cat /tmp/test.txt > test.txt

Finally, you should definitely take a look at these books to fuel your Docker knowledge: