Volumes: Keep Your Data
Data that survives containers.
Containers are disposable. When you delete one, everything written inside it is gone. That is great for apps, and terrible for databases. Volumes give containers a place to store data that lives on after the container is removed.
The problem, shown
docker run --name note alpine sh -c "echo hello > /data.txt" docker rm note note docker run --rm alpine cat /data.txt cat: can't open '/data.txt': No such file or directory
Named volumes
A named volume is storage managed by Docker. Mount it into a container with -v name:/path. Here a Postgres database keeps its data in the pgdata volume, so you can stop, delete and recreate the container without losing a single row.
docker volume create pgdata pgdata docker run -d --name db -e POSTGRES_PASSWORD=secret -v pgdata:/var/lib/postgresql/data postgres:16 5c2d... docker volume ls DRIVER VOLUME NAME local pgdata
Bind mounts for development
A bind mount maps a folder from your computer into the container. Edit a file in your editor and the container sees the change instantly, which is perfect while developing.
docker run -d -p 8080:80 -v "$(pwd)/site:/usr/share/nginx/html:ro" nginx:1.27 e8b1...
Named volume
- managed by Docker
- best for databases
- portable between machines
Bind mount
- any folder on your computer
- best for live code editing
- depends on your file paths
Try it yourself
Write a file into a volume from one container, delete it, then read the file from a brand new container.
Show hint
mount the same -v name:/data in both runs
Show solution
docker run --rm -v notes:/data alpine sh -c "echo saved > /data/n.txt"
docker run --rm -v notes:/data alpine cat /data/n.txtsaved
Summary
- Container files vanish when the container is removed
- Named volumes keep data, ideal for databases
- Bind mounts share a folder for development