Modifying the container layer

Before we dive into volumes, let's first discuss what's happening if an application in a container changes something in the filesystem of the container. In this case, the changes are all happening in the writable container layer. Let's quickly demonstrate this by running a container and execute a script in it that is creating a new file:

$ docker container run --name demo \
alpine /bin/sh -c 'echo "This is a test" > sample.txt'

The preceding command creates a container named demo and inside this container creates a file called sample.txt with the content This is a test. The container exits after this but remains in memory available for us to do our investigations. Let's use the diff command to find out what has changed in the container's filesystem in relation to the filesystem of the image:

$ docker container diff demo

The output should look like this:

A /sample.txt

Evidently a new file, Ahas been added to the filesystem of the container as expected. Since all layers that stem from the underlying image (alpine in this case) are immutable, the change could only happen in the writeable container layer.

If we now remove the container from memory, its container layer will also be removed and with it all the changes will be irreversibly deleted. If we need our changes to persist even beyond the lifetime of the container, this is not a solution. Luckily, we have better options in the form of Docker volumes. Let's get to know them.