Keep Data Beyond a Container · Docker
Compare the lifetime of a writable layer with a named volume.
Learn with progress and quizzesFirst, understand the concepts.
Writable layer
Files stored only in a container’s writable layer disappear when that container is removed. Starting the image again does not restore that layer.
Named volume
Named volumes are managed separately. A new container can read a file written by another container by mounting the same volume.
Read-only mount
A readonly mount prevents writes through that mount. Removing a volume is a separate operation; check whether its data should be kept first.
Why it matters
A volume separates data lifetime from container replacement. It lets you decide on deletion independently, but does not create a recovery copy by itself.
Work through the reasoning
Trace where data lives
The first container writes into a named volume. The next mounts that same volume and reads the file. The data is not surviving accidentally in the new container’s writable layer.
Understand mount visibility
At a mount destination, visible files come from the mounted storage. If expected files disappear, inspect volume names, destinations, and read-only flags.
Learn by doing.
Use Docker Engine or Docker Desktop with Linux containers, Compose v2, a POSIX shell, and curl on a personal practice host. Clean up only the study-prefixed resources you create. Pulling images requires network access.
Create study-data, write a file with the first container, and remove that container with --rm. Read the file from a fresh container.
docker volume create study-data
docker run --rm --mount type=volume,src=study-data,dst=/data busybox:1.36 sh -c 'echo persistent-note > /data/note.txt'
docker run --rm --mount type=volume,src=study-data,dst=/data,readonly busybox:1.36 cat /data/note.txt
docker volume inspect study-dataHow to check your result
The second container should print persistent-note. Inspect the volume to confirm it exists separately. Clean up only this practice volume rather than running a global prune.
Clean up practice resources
Run after checking the result. Confirm these resources belong to your practice run and contain no data you need to keep.
docker volume rm study-dataApply what you learned
Does sharing a volume automatically make simultaneous writes safe?
Reveal the reasoning after trying
No. Shared access and safe concurrency are different concerns. Applications may need locking or database concurrency controls. Use read-only mounts for readers and identify the intended writers.
Ready to check your understanding?
Why can a fresh container still read the file?
- The image was automatically changed
- Logs restored the file
- It is stored in a separately managed named volume
- --rm prevents all deletion
Reveal the reasoning after trying
It is stored in a separately managed named volume
The file is in a named volume, not the writable container layer. The named volume remains separately after --rm removes the container.