Chapter 7: Docker Volumes, Networks and Compose
7.2 Volumes vs bind mounts
Volume — Docker manages a named (or anonymous) storage area. Good default for databases in labs and many production setups.
Bind mount — map a host folder path into the container. Handy for live code reload on a laptop; riskier if paths differ between machines.
# named volume (preferred for DB data in this course)
docker volume create badge-api_pgdata
docker run -d --name badge-api-db \
-v badge-api_pgdata:/var/lib/postgresql/data \
-e POSTGRES_PASSWORD=lab-only-change-me \
postgres:16
| Type | Syntax idea | When to use |
|---|---|---|
| Named volume | -v badge-api_pgdata:/var/lib/postgresql/data |
DB files, durable lab data |
| Anonymous volume | -v /var/lib/postgresql/data (no name) |
Easy to lose track of — avoid for important data |
| Bind mount | -v "$PWD/app:/app" |
Local code edit while container runs |
What you see: docker volume ls lists badge-api_pgdata. After docker rm -f badge-api-db and a new docker run with the same -v name, data in Postgres still exists (same password/init assumptions).
Ravindra Bagale's Tip
Anonymous volume ne data "disappear" vatate — volume asel pan nave nahi, cleanup confusing. Named volume badge-api_pgdata sarakhe clear naav theva. Lakshat theva!
Practice task
In two sentences: when would you choose a named volume over a bind mount for badge API's Postgres data?