4

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.

Krzysztof Atłasik
  • 18,129
  • 4
  • 42
  • 64
subhash
  • 399
  • 2
  • 4
  • 19
  • 1
    Possible duplicate of [Copying files from host to Docker container](https://stackoverflow.com/questions/22907231/copying-files-from-host-to-docker-container) – Adiii Sep 09 '19 at 01:17
  • `docker cp : `. You can run this from the host machine – Jinna Balu Sep 09 '19 at 05:20

2 Answers2

5

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.

azbarcea
  • 1,977
  • 13
  • 17
0

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.

Ernesto Campohermoso
  • 6,844
  • 1
  • 34
  • 50