how `docker cp` command works

Viewed 1659

The command docker cp is used to copy files from host machine to container and vice versa. This command works even if container is in stop state or exited. Docker uses layered approach for storing images and when we run container by using this image, it creates one more writable layer above it which takes care of all the changes done inside the container. Once we exits from the container this writable layer gone. Here, I'm not able to find out, where docker stores the data of that container which is available for docker cp command even after container's exit . I searched /var/lib/docker directory, but no luck. I am using centos7.2 with devicemapper storage driver for docker. does anyone has any idea?

2 Answers

The docker container is not deleted when it exits, unless you use the --rm option. Instead, you can use docker cp to copy files to and from the container after it exits:

$ docker run --name run1 alpine sh -c "date > /tmp/test.txt"
$ docker cp run1:/tmp/test.txt test.txt
$ cat test.txt
Fri Oct  6 19:23:09 UTC 2017

You asked where those files are stored, so we need to do some digging. All of the docker data files seem to be under /var/lib/docker, so I looked around and found something under the overlay2 folder.

$ sudo ls -lt /var/lib/docker/100000.100000/overlay2
total 180
drwx------ 5 100000 100000 4096 Oct  6 12:23 bda6a77ed8fad218f738f32a149d4f9f9e46b103675b8b8f990f48e3339fd315
drwx------ 2 100000 100000 4096 Oct  6 12:23 l
drwx------ 5 100000 100000 4096 Oct  6 12:23 bda6a77ed8fad218f738f32a149d4f9f9e46b103675b8b8f990f48e3339fd315-init
drwx------ 3 100000 100000 4096 Oct  6 10:30 9c2aa6553beac112794143531e7760add2c94733898ae0674c5da30c3feb9451
...

There are many more folders there, but the most recent one probably has what we're looking for. The diff folder seems to hold all the files that changed between the image and the container. If I look in there, I find the file I created.

$ sudo ls -l /var/lib/docker/100000.100000/overlay2/bda6a77ed8fad218f738f32a149d4f9f9e46b103675b8b8f990f48e3339fd315/diff
total 4
drwxrwxrwt 2 100000 100000 4096 Oct  6 12:23 tmp
$ sudo ls -l /var/lib/docker/100000.100000/overlay2/bda6a77ed8fad218f738f32a149d4f9f9e46b103675b8b8f990f48e3339fd315/diff/tmp
total 4
-rw-r--r-- 1 100000 100000 29 Oct  6 12:23 test.txt
$ sudo cat /var/lib/docker/100000.100000/overlay2/bda6a77ed8fad218f738f32a149d4f9f9e46b103675b8b8f990f48e3339fd315/diff/tmp/test.txt
Fri Oct  6 19:23:09 UTC 2017
$ 

docker cp just does all the digging for me. Much easier. I'm using docker 17.09.0-ce, and I wouldn't be surprised if this internal structure changes from version to version.

Related