Docker – Copy file from container to host directory

Ok, so here is one very common question. How do I copy file from a docker image instance (container) to a host file system?

Why? One common scenario would be, for example, running a continuous integration server and running Cucumber tests. Once you generate the HTML report, you’d like to copy the file to host file system and then remove the image.

I have found at least two ways of doing this, but most reliable seems to be to mount a volume ie mount a directory from the host file system into a docker image instance file system. Let’s see an example of this.

In your Dockerfile, you would start your application, run the tests and create a report. Then, you’d copy the report to mounted directory. For example, something like this:

FROM base-image AS cucumber
EXPOSE 8080
CMD (npm start) & (/usr/bin/wait-for localhost:8080 -- echo "Node App is Up"; npm run cucumber) && (cp /usr/src/app/test/report/cucumber_report.html /artifacts)

Now, when running the docker image, you need to mount a directory to, in our exaple, /artifacts directory inside docker container.

docker run -i -v ${PWD}/:/artifacts --rm your-docker-image

Where -v would create a ‘volume’ and mount current directory (pwd – print working directory) to /artifacts directory.

If running on a Windows machine, try mounting the drive like so:

docker run –name mongo-pers-test –rm -v /Dimitar/dockerVolMongo/ContainerData:/data/db -p 27017:27017 -d mongo

Check the https://github.com/docker/for-win/issues/138.

https://docs.docker.com/storage/volumes/