In my daily work, I have utility containers. Some are based on ubuntu, others just on busy box. I start them, run few commands and destroy them.
For some specific task I need a long running container and populate it with files that are from the host. And after my work is done, I copy the result from the container back to the host.
The post used command is docker cp
According to the reference: Docker CLI docs for cp
, the cp
command is the best suited for this task. It is used to copy files.
Get the container’s ID
To know your container’s ID, you need to run this command:
docker ps
This command list all the running containers. Locate yours and note its ID.
Get the full container ID (optionnal)
To get the full container ID, run this command (replace SHORT_CONTAINER_ID-or-CONTAINER_NAME
with what is applicable to your container):
docker inspect -f '{{.Id}}' SHORT_CONTAINER_ID-or-CONTAINER_NAME
For example:
docker ps
Gives this response:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d8e703d7e303 solidleon/ssh:latest /usr/sbin/sshd -D cranky_pare
Then you can run this command to get the full ID:
docker inspect -f '{{.Id}}' cranky_pare
You get this result:
d8e703d7e3039a6df6d01bd7fb58d1882e592a85059eb16c4b83cf91847f88e5
Copy files from the host to the container
One specific file can be copied TO the container like:
docker cp foo.txt container_id:/foo.txt
Copy files from the container to the host (at the end of my tasks)
One specific file can be copied FROM the container like:
docker cp container_id:/foo.txt foo.txt
For emphasis, container_id
is a container ID, not an image ID. (Use <a class="wiki-link" href="/blog/en/kubernetes/can-docker-connect-to-database">docker</a> ps
to view listing which includes container_id
s.)
Multiple files contained by the folder src
can be copied into the target
folder using:
docker cp src/. container_id:/target
docker cp container_id:/src/. target
Note: In Docker versions prior to 1.8 it was only possible to copy files from a container to the host. Not from the host to a container.
Bonus : Copy files between two containers
To achieve that, you need to take two steps:
- Copy the file from the first container to the to the host.
- Copy the file from the host to the seconf container.
Here are the commands to run:
Copy from container 1 to host
docker cp container_id1:./bar/foo.txt .
Copy from host to container 2
docker exec -i container_id2 sh -c 'cat > ./bar/foo.txt' < ./foo.txt
Conclusion
That’s all. I hope you enjoyed this tutorial. Which commands do you often use in your daily work arround docker?
Let me know in the comments.
Graphics are from Ali Hallaji