The easiest way to copy files in a docker container to the host machine or vice versa is to use the
docker cp command. This command is very similar to the ‘cp’ command in Unix systems. Directories are copied with permission preserved as much as possible. The syntax is as follows.
How docker cp command is working?
You can copy files from the container file system to the host machine or the other way around with the help of docker cp command. The container can be stopped or in running mode.
Before starting the demo, let’s list our containers running with the
docker ps command.
Let’s create a sample.txt file on the host to copy. Then, using the above syntax copy this file to the /home folder in the running “nginx” container.
After copying the file, connect to the container with the command
docker exec -it <container_name> /bin/bash. Check it! Here is the sample.txt file under the /home folder.
We can also use container IDs instead of their names. The first four characters of ID is enough:
docker cp /home/ubuntu/sample.txt d759:/home
How to copy entire directory on host machine to the container?
It is also possible to copy an entire directory instead of a single file. This example copies the entire sample directory which consists of three files from the local host to /etc folder of the Nginx container. This time I will use the ID of the container rather than the name.
How to copy files from container to the host machine?
To copy files from the Nginx container to any directory on the host machine, we just switch the order of the parameters:
docker cp d759:/etc/sample /ubuntu/home
Don’t forget docker cp command does have a limitation. You cannot use it to copy between two containers. It can only be used to copy files between the host system and a single container.
Normally, The best practice is making containers immutable, and even making the Copy on Write (COW) layer to Read-Only(RO). But under development to be able to curate an ultimate image, to resolve an issue, for troubleshooting, and debugging purposes this kind of intervention is forgivebale.
Let us know which kind of method are you using for moving files between containers and host during development stage.