There are situations when you need to copy files/folders from the container’s file system to the local machine and vice versa. You can achieve that with Docker
copy command. In this tutorial, I’m going to cover these two scenarios.
- sudo privileges
Copying files/folders from local machine to a Docker container
Step 1. To copy the file from your host machine to the Docker container, you need to list the running containers and get the
id of the desired container.
sudo docker ps
Once you have the
id of the container, copy the file into the container. I will copy the file into the
/opt/ directory inside the container, but you can specify a different path depending on your needs.
sudo docker cp /home/devcoops/devcoops.txt 7d3055dd224c:/opt/
Note(s): If you do not specify the full path of your host file/folder, you will get an error:
no such file or directory.
Step 2. To copy a folder with all the files from your host machine to a Docker container, run:
sudo docker cp /home/devcoops/devcoopsdocker/ 7d3055dd224c:/opt/
Copying files/folders from Docker container to a local machine
Step 1. Copy a file from your Docker container to your host machine. I will use the same Docker container
id from the previous step.
sudo docker cp 7d3055dd224c:/opt/devcoops.txt /home/devcoops/
Step 2. Copy a folder with all the files from your Docker container to the host machine.
sudo docker cp 7d3055dd224c:/opt/devcoopsdocker/ /home/devcoops/
Note(s): If you try to copy
files/folders from one Docker container to another, for instance:
sudo docker cp 7d3055dd224c:/opt/devcoops.txt b9733ffea0ad:/opt/
It will throw an error that there is no possibility to copy files/folders between Docker containers.
copying between containers is not supported
cp command plays the same role as the Unix
cp command which is an easy operation. If you have any questions regarding the
docker cp command feel free to leave a comment below and follow our official channel on Telegram.