A container can write a file in its own writable layer. If you remove that container, Docker removes that layer. A named volume is storage that Docker manages separately. You can attach it to a replacement container.
Docker Compose · Lesson 4
Volumes
Learn why a named volume keeps files across container replacements.
Defining a Practice Volume
Save this separate example as compose.volume.yaml in the practice directory. It maps storage named notes to the path /data inside the toolbox. The bottom volumes section declares the named storage.
services:
toolbox:
image: busybox:1.36
volumes:
- notes:/data
volumes:
notes:
The service definition controls where the mount appears inside a container. The top-level declaration tells Compose to manage that volume with the project.
Which path inside the toolbox uses the named volume?
Writing and Reading with Separate Containers
The -f option selects the alternate file and -p gives it a separate project name. The run --rm command creates a one-off container and removes it after it finishes. Run these in the isolated practice folder. The first command overwrites the test file at /data/note.txt.
$ docker compose -p journey-volume -f compose.volume.yaml run --rm toolbox sh -c 'echo ready > /data/note.txt'
$ docker compose -p journey-volume -f compose.volume.yaml run --rm toolbox cat /data/note.txt
The second container should print ready. It mounts the same volume as the first one.
Why can the second container read the file after the first one was removed?

Keeping Data Intentional
A filename such as /tmp/note.txt outside the mounted directory stays with that container unless some other storage covers it. Inspect the paths before assuming a file is protected. Deleting the volume itself can erase its data. A backup is a separate copy that you can restore if the volume is lost.
Which file would the next toolbox container see through this volume?
Lesson complete
You finished Volumes
You can now explain why a file can outlive the container that wrote it.
Read the volume name and the mount path.
Verify persistence by reading the file from a separate container.
Keep volume deletion and container replacement distinct.
Keep your learning progress
Create a free account to save this lesson and continue learning on any device.
Create a free account