Volumes & Networks in Compose

Declare named volumes and custom networks at the top level of compose.yml and attach services to them.

Compose can manage volumes and networks for you. Declare them at the top level of the file, then reference them from services.

Named volumes

List volume names under a top-level volumes: key, then mount them in services. Compose creates them automatically and reuses them across restarts.

Custom networks

Define networks under a top-level networks: key to segment your app. Attach each service to the networks it needs, isolating tiers such as frontend and backend.

Example

Example · yaml
services:
  api:
    build: .
    networks:
      - frontend
      - backend
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: secret
    volumes:
      - pgdata:/var/lib/postgresql/data
    networks:
      - backend

volumes:
  pgdata:

networks:
  frontend:
  backend:

When to use it

  • A team declares a named volume in compose.yml so database data persists when they run docker compose down and back up.
  • A project uses separate frontend and backend networks so the Postgres container is not reachable from the public-facing web service.
  • A developer mounts source code into a service with a bind-mount volume for hot-reloading, while a named volume stores uploaded files.

More examples

Named volume in Compose

Declares a named volume at the top level and attaches it to the db service for persistent storage.

Example · yaml
services:
  db:
    image: postgres:16-alpine
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

Separate frontend and backend networks

Puts the database on the backend network only, so the web container cannot reach it directly.

Example · yaml
services:
  web:
    image: nginx:alpine
    networks: [frontend]

  api:
    build: ./api
    networks: [frontend, backend]

  db:
    image: postgres:16-alpine
    networks: [backend]

networks:
  frontend:
  backend:

Mix bind mount and named volume

Uses a bind mount for live code editing and a named volume for persistent upload storage in the same service.

Example · yaml
services:
  app:
    build: .
    volumes:
      # Bind mount: hot-reload source code
      - ./src:/app/src
      # Named volume: persist user uploads
      - uploads:/app/uploads

volumes:
  uploads:

Discussion

  • Be the first to comment on this lesson.