TExcelTAD
Home › Docker › Compose Volumes & Networks

Compose Volumes & Networks

Everything you learned about volumes and networks with docker run carries over to Compose, but declared in YAML. Compose creates the volumes and networks for you, prefixes them with the project name, and connects each service as you describe.

Volumes in Compose

yaml
services:
  db:
    image: postgres:17
    volumes:
      - pgdata:/var/lib/postgresql/data          # named volume
      - ./initdb:/docker-entrypoint-initdb.d:ro  # bind mount (relative to the compose file)
  api:
    build: .
    volumes:
      - type: bind
        source: ./src
        target: /app/src
      - type: tmpfs
        target: /tmp
  backup:
    image: alpine
    volumes:
      - pgdata:/data:ro
      - shared-certs:/certs

volumes:
  pgdata: {}               # created as <project>_pgdata
  shared-certs:
    external: true         # must already exist; Compose never creates or deletes it

The top-level volumes: section declares named volumes. A service may refer to a named volume only if it is declared there; paths starting with . or / are bind mounts. external: true points to a volume managed outside this project; name: sets an exact name without the project prefix.

python · try it yourself
import yaml

COMPOSE = """
services:
  db:
    volumes: ["pgdata:/var/lib/postgresql/data", "./initdb:/docker-entrypoint-initdb.d:ro"]
  backup:
    volumes: ["pgdata:/data:ro", "shared-certs:/certs", "logs:/var/log/app"]
volumes:
  pgdata: {}
  shared-certs: {external: true}
  reports: {name: "acme-reports"}
"""

project = "shop"
spec = yaml.safe_load(COMPOSE)
declared = spec.get("volumes", {})

def volume_name(key):
    options = declared[key] or {}
    if options.get("external"):
        return f"{options.get('name', key)} (external, must already exist)"
    return options.get("name", f"{project}_{key}")

for service, conf in spec["services"].items():
    for entry in conf["volumes"]:
        source, target = entry.split(":")[:2]
        if source.startswith((".", "/")):
            print(f"{service:<7} bind   {source:<14} -> {target}")
        elif source in declared:
            print(f"{service:<7} volume {volume_name(source):<14} -> {target}")
        else:
            print(f"{service:<7} ERROR  service \"{service}\" refers to undefined volume {source}")
print("declared but unused:", [k for k in declared
                               if not any(e.startswith(k + ":") for c in spec["services"].values() for e in c["volumes"])])
db      volume shop_pgdata    -> /var/lib/postgresql/data
db      bind   ./initdb       -> /docker-entrypoint-initdb.d
backup  volume shop_pgdata    -> /data
backup  volume shared-certs (external, must already exist) -> /certs
backup  ERROR  service "backup" refers to undefined volume logs
declared but unused: ['reports']

Warning: docker compose down -v deletes the project's named volumes, including your development database. External volumes are left alone.

Networks in Compose

Without a networks: section every service joins <project>_default. Declare your own networks to separate tiers:

yaml
services:
  proxy:
    image: nginx:1.27
    ports: ["80:80"]
    networks: [frontend]
  api:
    build: .
    networks:
      frontend: {}
      backend:
        aliases: [shop-api]
  db:
    image: postgres:17
    networks: [backend]

networks:
  frontend: {}
  backend:
    internal: true        # no route to the outside world
  • aliases adds extra DNS names for a service on that network.
  • internal: true blocks traffic leaving the network: the database can't reach the internet (and can't be reached from the host through it).
  • external: true joins a network created outside the project, a way to let two compose projects talk.

The model computes who can talk to whom from the file:

python · try it yourself
import yaml

COMPOSE = """
services:
  proxy: {networks: [frontend]}
  api:
    networks:
      frontend: {}
      backend: {aliases: [shop-api]}
  worker: {networks: [backend]}
  db: {networks: [backend]}
networks:
  frontend: {}
  backend: {internal: true}
"""

spec = yaml.safe_load(COMPOSE)

def nets(service):
    n = spec["services"][service].get("networks", ["default"])
    return set(n if isinstance(n, list) else n.keys())

def dns_names(service):
    names = {service}
    n = spec["services"][service].get("networks", {})
    if isinstance(n, dict):
        for options in n.values():
            names |= set((options or {}).get("aliases", []))
    return names

services = list(spec["services"])
for a in services:
    reachable = [b for b in services if b != a and nets(a) & nets(b)]
    print(f"{a:<7} can reach {reachable}")
print("names for api:", sorted(dns_names("api")))
internal = [n for n, o in spec["networks"].items() if (o or {}).get("internal")]
print("no internet access on:", internal)
proxy   can reach ['api']
api     can reach ['proxy', 'worker', 'db']
worker  can reach ['api', 'db']
db      can reach ['api', 'worker']
names for api: ['api', 'shop-api']
no internet access on: ['backend']

Sharing data between services

A named volume mounted into several services is a simple way to share files: one service writes, another reads. Mount it :ro in the readers. For anything more than files, such as a queue of jobs, use a proper service (Redis, a database) instead; two processes writing the same files concurrently need locking.

Development tip: code mounts with dependencies

A common development pattern bind-mounts the source but keeps the dependencies that were installed in the image:

yaml
services:
  web:
    build: .
    volumes:
      - .:/app                  # your code, live
      - /app/node_modules       # anonymous volume: hides the host's node_modules

Without the second line, the bind mount would hide the image's /app/node_modules (remember: bind mounts hide what is underneath). Compose's newer watch mode (develop.watch + docker compose watch) syncs files into the container without bind mounts and can rebuild when package.json changes.

Go deeper: Named Volumes, Networks and Service Discovery & DNS in the Docker Compose course.

Test yourself

In project shop, a service uses pgdata:/var/lib/postgresql/data and the top level declares pgdata: {}. What is the volume's real name?

  1. pgdata
  2. shop_pgdata
  3. shop-pgdata-1
  4. default_pgdata

What does internal: true on a Compose network do?

  1. Makes it faster
  2. Prevents containers on it from reaching networks outside it, such as the internet
  3. Hides it from docker network ls
  4. Encrypts the traffic

Why add - /app/node_modules next to - .:/app in a dev compose file?

  1. To speed up the network
  2. So the image's installed node_modules is not hidden by the bind mount
  3. To delete node_modules
  4. Compose requires it