Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a file from docker container to host

Tags:

docker

Is there any other way to copy a file or folder from docker container to host machine by running a command in the container?

All the other questions I read suggested running docker cp command on the host machine.

like image 898
bananagator Avatar asked Sep 09 '19 00:09

bananagator


2 Answers

May be also a duplication of Copying files from Docker container to host

You are right, that for copying files between container and host, you will always get the 2 options:

Option 1: use docker cp <containerid>:/<path> <host-path> (more)

The reason you cannot run this command from the container is because of encapsulation (containerization principle). As such the dependency is uni-directional. The host knows about the container, the container doesn't know about the host. As an analogy, think of the real containers from a ship, once the container is closed you cannot move the cargo from container to the ship from within the container - unless somebody from the ship decides to open it (of course, unless your container wasn't compromised and they made a hole in the container shell)

Option 2: use docker volumes (recommended - more)

In this case, you mount the <host-path> in the container (during the execution docker run - or is part of your orchestration) and the command you run is: cp <from> <to>. The container doesn't even know is actually a real path on the host.

There is also the question of why do you need to copy ?. Knowing that any path in the container is already on the host, you may just find that file/folder path using docker inspect <containerid> and copy from the /var/lib/docker/containers/<containerid>/<path>. So, giving the whole context of what type of data you want to copy and for what reason, and in what environment (DEV/PROD) may give you other options.

like image 192
azbarcea Avatar answered Oct 12 '22 11:10

azbarcea


Asumming that your container id is abc123 you can do

docker cp abc123:/path/to/file /host/destination/folder

If you want to share folder between host an container, the best option are VOLUMES.

If you can't destroy the container you always can install ssh client and use scp.

like image 45
Ernesto Campohermoso Avatar answered Oct 12 '22 11:10

Ernesto Campohermoso