How does Docker keep the image immutable

2.2k Views Asked by At

From the Docker documentation :

The Docker image is read-only. When Docker runs a container from an image, it adds a read-write layer on top of the image (using a UnionFS) in which your application runs.

How are changes reconciled across layers? If I change the content of a file, would Docker only keep track of delta or will it store the altered file in the new layer?

I looked at this discussion at superuser, but still not certain about the final image structure.

2

There are 2 best solutions below

0
On BEST ANSWER

If you have a file in a layer and modify it (using RUN, or COPY or ADD), a new layer is created with the new entire file, not delta. Even worse if you only change the permission attributes of the file, RUN chmod 400 file a new layer is created and the whole file content reside in this new layer.

Regards

0
On

Every layer, of the image is RO except the top RW container layer and any volume mounts that are outside of the layered filesystem. If you download lots of files in the first layer, and delete them in the second layer (container running on top of the first layer), the second layer contains a delete command, but the files still exist in the first layer. You can see the results of this with docker diff:

$ docker run -it --name busytest busybox
/ # echo "hello world" >/root/test.txt
/ # rm /bin/rpm
/ # rm /bin/timeout
/ # rm /bin/wall
/ # exit

$ docker diff busytest
C /bin
D /bin/rpm
D /bin/timeout
D /bin/wall
C /root
A /root/.ash_history
A /root/test.txt

The diff is the contents of the RO layer of the container. And when you build an image, each RUN command generates a layer from this that is stored as part of your final image.