Docker Compose — Volume Types

Three types of volume mounts in Docker Compose and when to use each.

Why / When to Use

Use when you need to persist data, inject config files, or share files between host and container without rebuilding the image.

Core Concept / Commands

1. Bind Mount — host file or directory

services:
  app:
    image: nginx
    volumes:
      - ./my-config.conf:/etc/nginx/nginx.conf  # single file
      - ./html:/usr/share/nginx/html            # directory

Behaviour: reflects live host changes inside the container. Best for config files and local dev.

2. Named Volume — managed by Docker

services:
  app:
    image: postgres
    volumes:
      - pgdata:/var/lib/postgresql/data
 
volumes:
  pgdata:

Behaviour: persists data between container restarts. Managed by Docker daemon, survives docker compose down. Best for databases and stateful data.

3. Read-Only Bind Mount

volumes:
  - ./config.yml:/app/config.yml:ro

Behaviour: container can read but not write to the file. Best for secrets and certs.

Config / secret injection patterns

services:
  app:
    volumes:
      - ./secrets.env:/run/secrets/app_secret
      - ./certs/ssl.crt:/etc/ssl/certs/ssl.crt:ro

Key Options / Variants

TypeSyntaxPersists?Live Changes?
Bind (dir)./host/path:/container/pathHost-dependentYes
Bind (file)./file.conf:/etc/file.confHost-dependentYes
Named volumevolname:/container/pathYesNo (Docker-managed)
Read-only./file:/path:roHost-dependentYes

Gotchas

  • Single file bind mount: host file must already exist before docker compose up, otherwise Docker creates it as a directory (not a file)
  • Directory bind mount over existing container dir: the container’s original directory contents are hidden (shadowed), not merged
  • Named volumes survive docker compose down; use docker compose down -v to also remove named volumes
  • Bind mounts use absolute or relative host paths; relative paths are relative to the docker-compose.yml location

Source

Conversation: “Docker compose volume file mounting” — 2026-05-14