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 ubuntuFrom 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_PATHdocker cp SRC_PATH CONTAINER:DEST_PATHFor 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:/tmpdocker cp /var/log/apt test-ubuntu:/tmpVerify the copied files inside the container:
docker exec -it test-ubuntu find /tmpOutput:
/tmp
/tmp/auth.log
/tmp/apt
/tmp/apt/eipp.log.xz
/tmp/apt/history.log
/tmp/apt/term.logFrom 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_PATHdocker cp CONTAINER:SRC_PATH DEST_PATHCreate a directory on the host to store copied files:
mkdir ~/testFor example, copy a single file and a directory from the container into the ~/test on the host:
docker cp test-ubuntu:/etc/debconf.conf ~/testdocker cp test-ubuntu:/etc/apt ~/testCheck the results:
find ~/testOutput:
/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