Does data in a Docker volume survive docker rm?
Yes. Removing a container does not remove its named volume. Anonymous volumes are also kept unless you use docker rm -v. Data is deleted only when you run docker volume rm or prune.
Explain it simply
The volume is the locker in the storage room; the container is the student who used it. When the student leaves the college, the locker and its contents stay until the warden clears it.
If you start a database with -v pgdata:/var/lib/postgresql/data, delete the container and start a new one with the same -v pgdata:..., your data is back. docker rm leaves named volumes alone. Anonymous volumes (created by a VOLUME instruction without a name) are also left behind, but are hard to find and pile up as 'dangling' volumes; docker rm -v removes them with the container. docker volume prune removes all volumes no container uses, so be careful.
With Compose, docker compose down keeps volumes, while docker compose down -v deletes them.
Example
docker run -d --name db -v pgdata:/var/lib/postgresql/data postgres:16
docker rm -f db
docker volume ls # pgdata still listed
docker run -d --name db2 -v pgdata:/var/lib/postgresql/data postgres:16
docker volume rm pgdata # now it is really goneWhat to say in the interview
"Yes, named volumes outlive containers. Only docker volume rm, prune, docker rm -v for anonymous volumes, or compose down -v delete the data, so I check before using those."
Common mistakes
- Running docker compose down -v on a stack holding the only copy of the data.