Linux Labs

Containers: Docker and compose / Stage 5 of 11

Volumes: data outlives the container

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 7 · theory · 5 min

The container layer

Here is where a container keeps what its process writes, and why docker rm deletes it.

Image layers are read-only: many containers run from one image, and none of them may change it. So when docker creates a container, it puts one more empty layer on top of the image layers — the container layer. Everything the process creates, changes or deletes goes there. docker diff shows what has piled up in it:

text
$ sudo docker diff notes
C /data
A /data/notes.txt

A means a file was added, C changed, D deleted. The /data directory came from the image, while notes.txt appeared in the container.

The container layer lives as long as the container. docker stop, docker start and docker restart leave it alone: the notes are still there after them. docker rm removes the container together with its layer, and docker run creates a new container with a new empty layer on top of the same image. That is why /data turned out empty.

Check yourself 1 question

The web container serves a page from the site:2 image. You fixed it right inside — sudo docker exec web sh -c 'echo fixed > /www/index.html' — then re-created web from site:2. What will the site serve?

  • index.html sits in the site:2 image layer, which docker rm does not touch. Only the fix on top of it went away.

  • The image is read-only: docker exec changed the container layer, and site:2 stayed the same.

  • It was written to the container layer, and docker rm removed that layer. The new container got /www/index.html from the image.

The fix made through docker exec went into the container layer and was removed with it. The new container from site:2 serves the page from the image — a lasting fix goes into the Dockerfile and a new image.

Key points

  • Image layers are read-only; everything the process writes goes into the container layer.
  • docker stop, start and restart keep the layer, while docker rm removes it with the container.
  • docker diff shows what the container has changed on top of the image.
Ubuntu 24.04
Loading…