Docker volumes and bind mounts

Topic: Containers core

Summary

Persist container data with volumes (managed by Docker) or bind mounts (host path). Use named volumes for database data; use bind mounts for config or source code in dev. Use this when you need data to survive container removal or when mounting host files into a container.

Intent: How-to

Quick answer

  • Named volume: docker volume create mydata; docker run -v mydata:/app/data image. Data lives in Docker storage; survives container rm. List: docker volume ls; inspect: docker volume inspect mydata.
  • Bind mount: docker run -v /host/path:/container/path image. Host path must exist; container sees host files. Use for config (read-only :ro) or dev (mount source). Paths are host-dependent.
  • Compose: volumes: - mydata:/app/data (named) or - ./config:/app/config:ro (bind). Do not use bind mount for database data in production (use named volume); backup named volumes from host or from a sidecar.

Prerequisites

Steps

  1. Create and use named volume

    docker volume create pgdata. docker run -d -v pgdata:/var/lib/postgresql/data postgres:16. Data persists after docker rm. Backup: run a container that mounts the volume and tars it or use pg_dump from a postgres container.

  2. Bind mount for config

    docker run -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf:ro nginx. :ro makes it read-only. Host path must exist. Use for config files so you can edit on host without rebuilding image.

  3. Compose volumes

    volumes: - pgdata:/var/lib/postgresql/data in service; top-level volumes: pgdata:. For bind: - ./data:/app/data. Avoid binding critical host dirs (e.g. /) into container.

  4. Inspect and backup

    docker volume inspect pgdata shows mount point on host. To backup: docker run --rm -v pgdata:/data -v $(pwd):/backup alpine tar czf /backup/pgdata.tar.gz -C /data .

Summary

Use named volumes for persistent data (e.g. DB); use bind mounts for config or dev source. Use this to persist and share data between host and containers.

Prerequisites

Steps

Step 1: Create and use named volume

Create a volume and mount it in the container; data persists after container removal.

Step 2: Bind mount for config

Mount a host path into the container; use :ro for read-only config.

Step 3: Compose volumes

Define named volumes and bind mounts in the compose file; use named volumes for DB data.

Step 4: Inspect and backup

Inspect volume location; backup by mounting volume in a temporary container and archiving.

Verification

  • Data in a named volume survives container removal; bind-mounted files are visible in the container; backup and restore work.

Troubleshooting

Permission denied in container — Host path ownership may not match container user; fix with chown or run container as root (dev only). Volume not found — Create the volume first or let Docker create it on first run with that name.

Next steps

Continue to