Skip to content

Image VS Container; persistence of writable layer inside a container

Spring Ep edited this page Sep 25, 2020 · 1 revision

A container represents a running image. It has an additional layer at top of the image called the writable layer.

Docker container - writable layer

During the runtime of the container, all changes such as adding, modifying, or deleting files, will be stored in that writable layer. When the container is stopped, the writable layer will be preserved, and by restarting the container, it can access the same writable layer as it did before. The same goes for exiting the container.

Restore the container's content after exiting it

docker run -it --name test4 alpine:latest /bin/sh

We started a test container interactively. Next, inside the container, we ran mkdir -p /home/spring/test/ and touch /home/spring/test/file.txt, just to create some new directories and files inside the container's filesystem.

Next, we'll exit the container and when we run docker ps -a we can observe the state of the test4 container:

c8ccaffd63f0 alpine:latest "/bin/sh" 2 minutes ago Exited (0) 6 seconds ago test4

We can see that the container's state is set to Exited

We start this container again by running docker start -i test4. Inside the container, we can run ls /home/spring/test/, which will list the contents of the test directory and show that the file.txt resides there.
This shows that the writable layer of the container persists even after the container exits and starts again.


Make Docker automatically clean up the container

But, we can make Docker to automatically clean up the container after it exits, by using the --rm directive.

docker run --rm -it --name rm-test4 alpine:latest /bin/sh
This container will get deleted as soon as we exit from it. And we can't start it again because its filesystem got removed completely.