Opscraft
Docker Compose · Lesson 5 of 10 · 3 min read

Volumes and data

Named volumes vs bind mounts in Compose

services:
  db:
    volumes:
      - pgdata:/var/lib/postgresql/data      # named volume: persistent, Docker-managed
      - ./db/init:/docker-entrypoint-initdb.d:ro   # bind mount: host files
  api:
    volumes:
      - ./api/src:/app/src                   # live code reload in dev
      - /app/node_modules                    # anonymous volume: keep image's node_modules
volumes:
  pgdata: {}
  shared-cache:
    external: true                           # created outside this project
  • Named volumes persist across down/up. docker compose down -v deletes them — the most common "I lost my dev database" mistake.
  • The anonymous-volume trick (/app/node_modules) stops a bind mount of the source tree from hiding dependencies installed in the image.
  • Postgres/MySQL images run init scripts in /docker-entrypoint-initdb.d only when the data directory is empty. Changed your seed SQL but nothing happens? The volume already has data — remove the volume to reseed.
  • Bind mounts on macOS/Windows are slower because files cross into Docker Desktop's Linux VM; use synchronized file shares or docker compose watch for large trees.
  • Permission errors on bind mounts come from UID mismatches between the host directory owner and the container user.
Enlarge diagramNamed volume · pgdata:Bind mount · ./src:/app/srcDocker manages where it livesSurvives down; removed by down -vUse for databases and cachesYour folder, shown inside the containerEdits appear instantly: great for developmentWatch out for file ownership (UIDs)
Figure 1. Named volumes keep data between runs; bind mounts put your source code inside the container for live editing.
Swipe sideways to see all of it, or tap to open it full screen.