I want to copy some file from a docker image without actually running a container from that image. Is it possible to do so? If yes, what would be steps required ?
Asked
Active
Viewed 6,538 times
4 Answers
21
There's not a docker cp for images because images are inmutable objects but:
you can create a non running container:
docker create --name cont1 some-image
docker cp cont1:/some/dir/file.tmp file.tmp
docker rm cont1
The full not accepted (now rejected) proposal for docker cp on images is here:

Alfonso Tienda
- 3,442
- 1
- 19
- 34
-
Docs for copying file out of a running container: https://docs.docker.com/engine/reference/commandline/cp/ – djeikyb Mar 05 '23 at 23:42
-
1Or not running, docker cp behaves the same. Just adapt to the solution. – Alfonso Tienda Mar 06 '23 at 13:40
3
Here's a one-liner to copy a file from a Docker Image, through a container:
Image defines CMD
docker run --rm \
-v $(pwd):/binary my-image /bin/sh -c "cp /kube-bench /binary"
Image defines ENTRYPOINT
docker run --rm --entrypoint "/bin/sh" \
-v $(pwd):/binary kube-bench-image -c "cp /kube-bench /binary"
Both commands mounts the current directory in order to copy the file /kube-bench
to it.

Marcello DeSales
- 21,361
- 14
- 77
- 80
-
This answer does the same as the selected answer https://stackoverflow.com/a/48265968/577001 but within a single line. Is there any reason this answer is less favorable? – IsaacS Nov 25 '19 at 21:15
-
@IsaacS if you are automating something, the fewer lines the better (in maintenance costs perspective) – Marcello DeSales Nov 26 '19 at 17:46
-
1My question can be rephrased as "Why is this answer not the chosen one" :) ? – IsaacS Dec 04 '19 at 21:28
-
actually the others answers do not trust in a file inside the image. `/bin/sh` can not be present in images `FROM SCRATCH`. And this one need to run the container. So it's not a response to the question that ask *without actually running the container*. – ton Oct 02 '20 at 22:41
1
docker image save alpine -o alpine.tar
untar, it will have a hash named directory and inside there is a layer.tar which contains the image files.

jhernandez
- 847
- 5
- 9
-
to extract all files in a image: `docker image save alpine | tar xvf - | grep layer.tar | xargs -i tar xvf {}` – ton Oct 02 '20 at 22:35
1
The Alfonso Tienda response do not work with image without CMD or Entrypoint.
The jhernandez is a good start point to a solution, but it need to extract all files.
What about:
docker image save $IMAGE |
tar tf - |
grep layer.tar |
while read layer; do
docker image save $IMAGE |
tar -xf - $layer -O |
tar -xf - $FILENAME ; done
So, we can just set the IMAGE
and FILENAME
to extract like:
$ IMAGE=alpine
$ FILENAME=etc/passwd
$ docker image save $IMAGE | tar tf - | grep layer.tar | while read layer; do docker image save $IMAGE | tar -xf - $layer -O | tar -xf - $FILENAME ; done
And we can save a some storage space.

ton
- 3,827
- 1
- 42
- 40