Copy Files and Directories Between Host and Docker Container

Copy Files and Directories Between Host and Docker Container

When working with Docker, there are times when you need to move files between your local machine (the host) and a container. For example, you might want to push configuration files or application code into a container for testing, or pull logs and generated data back to the host for analysis. While Docker volumes are generally the recommended way to persist and share data, there are situations where a quick, one-off copy is all you need. This tutorial explains how to copy files and directories between host and Docker container.

Start Ubuntu container for testing purposes:

docker run -dit --name=test-ubuntu ubuntu

From host to container

We can copy files or directories from the host machine into a container using docker container cp (shortcut docker cp) command. The syntax:

docker container cp SRC_PATH CONTAINER:DEST_PATH
docker cp SRC_PATH CONTAINER:DEST_PATH

For example, copy a single file and a directory from the host into the /tmp inside the container:

docker cp /var/log/auth.log test-ubuntu:/tmp
docker cp /var/log/apt test-ubuntu:/tmp

Verify the copied files inside the container:

docker exec -it test-ubuntu find /tmp

Output:

/tmp
/tmp/auth.log
/tmp/apt
/tmp/apt/eipp.log.xz
/tmp/apt/history.log
/tmp/apt/term.log

From container to host

We can also copy files or directories from a container back to your host. The syntax:

docker container cp CONTAINER:SRC_PATH DEST_PATH
docker cp CONTAINER:SRC_PATH DEST_PATH

Create a directory on the host to store copied files:

mkdir ~/test

For example, copy a single file and a directory from the container into the ~/test on the host:

docker cp test-ubuntu:/etc/debconf.conf ~/test
docker cp test-ubuntu:/etc/apt ~/test

Check the results:

find ~/test

Output:

/home/ubuntu/test
/home/ubuntu/test/debconf.conf
/home/ubuntu/test/apt
/home/ubuntu/test/apt/preferences.d
/home/ubuntu/test/apt/sources.list
/home/ubuntu/test/apt/auth.conf.d
/home/ubuntu/test/apt/keyrings
...

Leave a Comment

Cancel reply

Your email address will not be published.