Docker Tutorial · Data and Networking · Lesson 15 of 26
Volumes: Keeping Data
Container filesystems are temporary; named volumes keep databases and uploads across container replacements.
Why volumes
Anything a container writes to its own filesystem disappears when the container is removed, and replacing containers is routine (new image versions, restarts on other hosts). Volumes are storage managed by Docker that lives independently of containers:
docker volume create pgdata
docker run -d --name db -v pgdata:/var/lib/postgresql postgres:18-alpine
Remove and recreate the container with the same -v pgdata:... and the data is still there.
| Volume | Bind mount | Container layer | |
|---|---|---|---|
| Managed by | Docker | You (host path) | Docker, per container |
| Survives container removal | Yes | Yes | No |
| Typical use | Databases, uploads | Source code in development, config files | Temporary files |
trap 'docker rm -f rc-vol-a rc-vol-b > /dev/null 2>&1; docker volume rm rc-notes > /dev/null 2>&1' EXIT
docker volume create rc-notes > /dev/null
docker run --name rc-vol-a -v rc-notes:/data alpine:3.24 sh -c 'echo "first note" > /data/notes.txt; echo "scratch" > /tmp/scratch.txt'
docker rm rc-vol-a > /dev/null
docker run --name rc-vol-b -v rc-notes:/data alpine:3.24 sh -c 'cat /data/notes.txt; ls /tmp/scratch.txt 2>&1 | sed "s/^ls: //"'
echo "volume driver: $(docker volume inspect rc-notes --format '{{.Driver}}')"
Output
first note /tmp/scratch.txt: No such file or directory volume driver: local
Run this on your computer — see “Get Started” for setup.
See Volumes.
Test yourself
You upgrade a database container by removing it and starting a new one from a newer image. Where must the data live?
In the container's filesystemIn a volume mounted into both containersIn the imageIn an environment variable
Show answer
Answer: In a volume mounted into both containers
The old container's writable layer is deleted with it.