docker volume mount and bind mount — how to use

# Bind mount — map a host directory into the container
docker run -v $(pwd)/data:/app/data my-image

# Named volume — Docker manages the storage
docker run -v my-volume:/app/data my-image

# Read-only mount
docker run -v $(pwd)/config:/app/config:ro my-image

You need persistent data storage, or to share files between the host and a container.

Create and inspect named volumes

# Create
docker volume create my-volume

# List
docker volume ls

# Inspect (shows mount path on host)
docker volume inspect my-volume

--mount syntax (more explicit)

# Bind mount
docker run --mount type=bind,source=$(pwd)/data,target=/app/data my-image

# Named volume
docker run --mount type=volume,source=my-volume,target=/app/data my-image

Docker Compose volumes

# docker-compose.yml
services:
  db:
    image: postgres:16
    volumes:
      - pg-data:/var/lib/postgresql/data
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro

volumes:
  pg-data: