Volumes vs Bind Mounts
Volumes and bind mounts both keep data outside a container, but they differ in who owns the files. Docker owns a volume, and you own a bind-mounted folder.
A volume for a database
The database owns its data, so a volume fits.
docker run -d --name g5-db -v g5-pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=secret postgres:16-alpineA bind mount for code
You own the code, so a bind mount fits.
docker run -d --name g5-web -v ~/site:/usr/share/nginx/html:ro nginx:1.27-alpineExample
docker volume create g5-pgdata
docker run -d --name g5-db -v g5-pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=secret postgres:16-alpine >/dev/null
docker volume ls --filter name=g5-pgdata --format "{{.Name}} {{.Driver}}"Key points
- Volume: Docker owns the files, and they live in Docker's store.
- Bind mount: you own the files, and they live in a folder you chose.
- Use a volume for data the app owns, like a database.
- Use a bind mount for files you edit, like source code.
- A volume works the same on any machine. A bind mount needs the folder to exist.
In this example, Postgres runs with its data in a named volume. The listing shows the volume Docker manages. The database owns the data, so a volume is the right store, and a bind mount would be the wrong one.
Note
Backing up a volume means copying Docker's store. Backing up a bind mount means copying your folder.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Which store fits a database best?