9

I have a docker container which is running fine. It generates a few files in the directory /Project/userfiles.txt. I need these files for some testing purpose. But when this container is stopped everything is deleted. So I need to copy this file from the container to host.

I have a python application running in the container which is generating the file. I want some command or any way through which I can send the userfiles.txt to host at the end when the container is stopped.

To do this I can use docker cp command and I tried it but it gave me an error docker not found as docker is not installed.

How can I share files from container to host?

Wolfgang Fahl
  • 12,097
  • 9
  • 75
  • 150
Anna Carolina
  • 315
  • 2
  • 3
  • 7
  • Where are you running `docker cp` ? – vivekyad4v Dec 27 '17 at 12:47
  • @vivekyad4v Sorry I forgot to mention, I was running docker cp in container as my code is running there and this command I mentioned inside code. – Anna Carolina Dec 27 '17 at 12:48
  • You can run it on the host itself. Any specific reason to run it inside the container? – vivekyad4v Dec 27 '17 at 12:49
  • Possible duplicate of [Copying files from host to Docker container](https://stackoverflow.com/questions/22907231/copying-files-from-host-to-docker-container) – chenrui Dec 27 '17 at 13:25
  • Possible duplicate of [Copying files from Docker container to host](https://stackoverflow.com/questions/22049212/copying-files-from-docker-container-to-host) – Shubham Nov 30 '18 at 05:52

2 Answers2

12

Use docker cp on the host & not inside the container. In your case the command may look as below -

$ docker cp mycontainer:/Project/userfiles.txt userfiles.txt

After command completion you will get the file on host in the directory where you ran the docker cp command.

PS - I just checked that it works even if your container is in stopped state. For instance -

$ docker cp 9059e95cbe33:/etc/rc.local rc.local

9059e95cbe33 - Exited container ID/Name 
Shubham
  • 2,531
  • 3
  • 19
  • 33
vivekyad4v
  • 9,723
  • 4
  • 33
  • 49
5

Use a volume (a bind mount one) to make sure the files written in /Project are persisted.

volumes

That means you need to docker run your image with a -v /host/path:/Project option.
See "Use bind mounts" for the simplest approach (which is to share a host folder with your container)

VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283