Card 02/ 05
Writable Layer Example: A File That Does Not Survive docker rm
Restarting the container keeps the file; removing the container deletes it.
Writing a file inside a container, then restarting and removing the container, shows exactly when the writable layer, the container's private area for changed files, survives: restarting keeps it, and removing deletes it. The example uses alpine, a very small Linux image, kept running with sleep 600 (wait ten minutes) so there is time to work inside it.
The first command starts the container, the second writes the word important to /data.txt inside it, and the third reads the file back:
docker run -d --name box alpine sleep 600
docker exec box sh -c 'echo important > /data.txt'
docker exec box cat /data.txt
importantRestarting keeps the file, because a restart stops the program and starts it again without touching the container or its layer:
docker restart box
docker exec box cat /data.txt
importantRemoving the container is what takes the layer with it. -f forces the removal of a running container:
docker rm -f box
docker run --rm alpine cat /data.txt
cat: can't open '/data.txt': No such file or directoryThe second container came from the same image and saw only the image, which never had /data.txt. The --rm on that last command is the same rule stated in advance: remove this container as soon as it exits.
So stopping and restarting are safe, and docker rm is final for anything written inside the container. If the file mattered, it should have been written to a mount: a directory from your machine or a Docker volume attached to the container, which outlives it.
← → move through sections and cards