Back to roadmaps docker-compose Course

Shared Volumes and Network Isolation in Compose

Docker Compose allows you to declare top-level volumes and networks blocks, which are created automatically when you run docker compose up and are shared across your services.


1. Declaring Named Volumes

Define named volumes at the top level of your docker-compose.yml file. Then mount them inside individual services using the volumes key:

services:
  database:
    image: postgres:16-alpine
    volumes:
      # Mount named volume to Postgres data directory
      - postgres-data:/var/lib/postgresql/data

# Declare the named volume at the top level
volumes:
  postgres-data:

When you run docker compose down, the volume data is preserved. To delete it along with containers, use docker compose down -v.


2. Declaring Custom Networks

By default, Compose creates a single network for all services. You can isolate service groups by declaring multiple custom networks:

services:
  frontend:
    image: nginx:alpine
    networks:
      - public-net

  api:
    image: node:20-alpine
    networks:
      - public-net   # Can receive requests from frontend
      - private-net  # Can communicate with database

  database:
    image: postgres:16-alpine
    networks:
      - private-net  # Isolated from frontend; only accessible by api

# Declare top-level networks
networks:
  public-net:
  private-net:

This pattern ensures that your database is never directly reachable from the public-facing frontend service.

Published on Last updated: