पाठ 14 / 25

Named Volumes Versus Bind Mounts

Docker-managed data or your files.

Two kinds of mounts

A named volume (declared under top-level volumes) is storage managed by Docker that survives container recreation, the right place for database data. A bind mount maps a host path into the container, typically to mount source code during development so changes appear without rebuilding. Bind mounts depend on the host's files and permissions, so avoid them for production data. docker compose down keeps named volumes; down -v deletes them.

Persist data, share code, protect credentials

Named volumes keep data, bind mounts share files from the host, and secrets deliver credentials as files.

Three ideas: volumes versus bind mounts, secrets, backups.
Figure 5.1 — Volumes, secrets and backups.

Mounts in the resolved configuration, run

I ran this with Docker Compose v2.38.1 and jq in the demo "shop" project. docker compose config parses, interpolates, merges and validates the files without starting containers; the Docker daemon was not running, so nothing was started. The database uses the named volume db-data for its data directory; the API (through the development override) bind-mounts its source code into /app.

docker compose config --format json | jq -c "[.services.db.volumes[] | {type, source, target}], [.services.api.volumes[] | {type, target}], (.volumes | keys)"

Output:

[{"type":"volume","source":"db-data","target":"/var/lib/postgresql/data"}]
[{"type":"bind","target":"/app"}]
["db-data"]

Use named volumes for databases

Bind-mounting a database directory from the host often causes permission and performance problems.

त्वरित जाँच: Which mount type suits PostgreSQL data in Compose?

  • A tmpfs mount
  • A bind mount of the source code folder
  • No mount; keep data in the container layer
  • A named volume
Answer

A named volume — Named volumes persist and are managed by Docker.