Before you begin

In this tutorial will learn how to copy files from your host to a Docker container and the other way around. A Linux machine and Docker will be required to follow this tutorial.

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

Copy file from host to a Docker container

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

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

$ 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 to a Docker container

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

# 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 <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