Why does data disappear when a container is removed and how do volumes fix that?
Model answer
A container's files live in a thin writable layer on top of the read-only image. That layer belongs to the container, so when the container is removed, the layer and everything written there are deleted. Containers are meant to be disposable.
A volume is storage managed by Docker, outside the container's layer. You mount it at a path inside the container, so data written there survives the container's removal and can be mounted into a new container.
docker run -d --name db -v pgdata:/var/lib/postgresql/data \
-e POSTGRES_PASSWORD=secret postgres:17
docker rm -f db
docker run -d --name db -v pgdata:/var/lib/postgresql/data \
-e POSTGRES_PASSWORD=secret postgres:17 # the data is still there
Useful commands: docker volume ls, docker volume inspect pgdata and docker volume rm pgdata. A volume with no name is anonymous and easy to lose track of, so prefer named volumes.
Anything the container must keep, such as database files or uploads, goes on a volume or in an external service.
The container is disposable, so the data must live somewhere else.
Key points
- Container files live in a writable layer
- Removing the container deletes that layer
- A volume lives outside the container and can be re-mounted
- Prefer named volumes over anonymous ones
Likely follow-ups
- What is the difference between docker rm and docker rm -v?
Common mistakes
- Running a database without a volume and losing data on recreate
- Using docker compose down -v without realizing it deletes volumes