Volumes

A volume is storage managed by Docker that lives outside any container. Mount it where an app writes its data, and the data survives docker rm, upgrades and recreated containers.

How it works

docker run -v pgdata:/var/lib/postgresql/data creates the named volume pgdata if needed and mounts it. The first time, an empty volume is filled with what the image had at that path. Volumes are only deleted by docker volume rm, docker compose down -v or a prune.

What breaks

Mount the volume on the exact path where the program writes: a typo creates a volume nobody uses while the data stays in the writable layer. And images that declare VOLUME get a new anonymous volume for each container, easy to lose track of.

In a terminal

docker volume create pgdata
docker run -d --name db -e POSTGRES_PASSWORD=example -v pgdata:/var/lib/postgresql/data postgres:16
docker volume ls

See it break, then fix it

Write the Dockerfile or the compose file, type the docker commands, and watch a simulated server run them through reboots, upgrades and traffic. Free to start.