Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker - how can I copy a file from an image to a host?

My question is related to this question on copying files from containers to hosts; I have a Dockerfile that fetches dependencies, compiles a build artifact from source, and runs an executable. I also want to copy the build artifact (in my case it's a .zip produced by sbt dist in '../target/`, but I think this question also applies to jars, binaries, etc.

docker cp works on containers, not images; do I need to start a container just to get a file out of it? In a script, I tried running /bin/bash in interactive mode in the background, copying the file out, and then killing the container, but this seems kludgey. Is there a better way?

On the other hand, I would like to avoid unpacking a .tar file after running docker save $IMAGENAME just to get one file out (but that seems like the simplest, if slowest, option right now).

I would use docker volumes, e.g.:

docker run -v hostdir:out $IMAGENAME /bin/cp/../blah.zip /out

but I'm running boot2docker in OSX and I don't know how to directly write to my mac host filesystem (read-write volumes are mounting inside my boot2docker VM, which means I can't easily share a script to extract blah.zip from an image with others. Thoughts?

like image 690
Mark Avatar asked Oct 09 '22 12:10

Mark


People also ask

Can you extract files from a docker image?

There are severall ways to achive what you want… – export the image, extract it and the archives inside it and get your file: docker save repo:tag > image. tar then tar xf image. tar to extract files of the tar.

How do I export a file from a container?

To export a container, we use the docker export command. The documentation describes export as follows: docker export – Export a container's filesystem as a tar archive. As we can see, this is just a regular old Linux file system — the BusyBox file system created when running our image, to be precise.


2 Answers

To copy a file from an image, create a temporary container, copy the file from it and then delete it:

id=$(docker create image-name)
docker cp $id:path - > local-tar-file
docker rm -v $id
like image 320
Igor Bukanov Avatar answered Oct 12 '22 01:10

Igor Bukanov


Unfortunately there doesn't seem to be a way to copy files directly from Docker images. You need to create a container first and then copy the file from the container.

However, if your image contains a cat command (and it will do in many cases), you can do it with a single command:

docker run --rm --entrypoint cat yourimage  /path/to/file > path/to/destination

If your image doesn't contain cat, simply create a container and use the docker cp command as suggested in Igor's answer.

like image 100
fons Avatar answered Oct 12 '22 01:10

fons