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 3 of 7 · on a machine · 7 min

A named volume

You will move /data out of the container into a volume, and the notes will survive re-creation.

A volume is a directory that docker manages separately from the container's layers. The -v name:path option attaches it inside a container:

bash
sudo docker run -d --name notes -p 8080:8080 -v notes-data:/data notes:1

notes-data is the volume's name, /data is where it goes inside. There is no volume with that name yet, so docker creates it. Everything the process writes to /data goes into the volume, bypassing the container layer. docker rm removes the container, the volume stays, and the next container with the same -v sees the same files.

docker volume ls lists volumes, and the Mounts section of docker inspect shows a container's attachments.

Exercise · do it

Keep the notes in a volume

Re-create the notes container with the notes-data volume in place of /data (same port 8080), write any note to /data/notes.txt and re-create the container once more. The note must stay.

Sign in and start The machine is available after signing in

Goals · 0 of 2

  • Attach the notes-data volume to notes not done yet
  • Write a note and re-create the container not done yet

The volume lives on the host — the machine docker runs on — in docker's directory: sudo docker volume inspect notes-data shows the line "Mountpoint": "/var/lib/docker/volumes/notes-data/_data". The files there are ordinary host files. Their owner is whoever the process in the container writes as; for notes that is root, and sudo ls -l in that directory shows root root. docker volume rm notes-data removes the volume once it is no longer needed.

Check yourself 1 question

The notes container with the notes-data volume is running. What will sudo docker volume rm notes-data print?

  • There is no deferred removal: the command answers volume is in use at once, and the volume stays.

  • There is no question: the command prints the volume is in use error with the container ID right away.

  • docker does not remove an attached volume: Error response from daemon: remove notes-data: volume is in use.

docker does not remove an attached volume — the answer says volume is in use with the container ID. First the container goes, then docker volume rm.

Step goals

0 of 2
  • Attach the notes-data volume to notes — not done yet
  • Write a note and re-create the container — not done yet
Ubuntu 24.04

Step goals

0 of 2
  • Attach the notes-data volume to notes — not done yet
  • Write a note and re-create the container — not done yet
Loading…