Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 111 ยท Docker Compose

Networks and Volumes in Compose

Learn how Compose creates the default network, how to design front-end and back-end networks, and how named volumes, bind mounts, tmpfs and external resources behave.

Containers are disposable, but the way they find each other and the data they keep are not. In Compose you describe both in the same file as your services: networks decide who can talk to whom, and volumes decide what survives when a container is replaced. Two top-level keys, networks and volumes, sit next to services and are referenced from inside each service.

This lesson shows what Compose creates for you without being asked, how to take control when you need to, and the one flag (down -v) that decides whether your data lives or dies. It builds on User-Defined Bridge Networks and Volumes. All output comes from a real Docker 29 and Compose v5.

The default network

You can write a Compose file with no networks key at all. Compose then creates one network named <project>_default, attaches every service to it, and registers each service name in Docker's embedded DNS. That is a user-defined bridge, so everything you learned about automatic DNS applies.

YAML
name: tcd-b9-nv
services:
  api:
    image: alpine:3
    command: ["sleep", "600"]
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_PASSWORD: example
CONSOLE
$ docker compose up -d
$ docker network ls --filter name=tcd-b9-nv --format '{{.Name}} {{.Driver}}'
tcd-b9-nv_default bridge
$ docker compose exec api ping -c1 db
PING db (172.21.0.3): 56 data bytes
64 bytes from 172.21.0.3: seq=0 ttl=64 time=0.9 ms

The api container reached the database simply by writing db. That is the whole trick behind a connection string such as postgres://db:5432/shop. Remember that on the network you use the container port (5432), not any host port you published.

For a small project the default network is all you need. Add custom networks only when you want isolation.

Designing your own networks

The moment a stack has a public-facing piece and a private piece, separate networks pay off. The usual layout is a front network for what the proxy can see and a back network for the data tier:

YAML
name: tcd-b9-nv
services:
  proxy:
    image: alpine:3
    command: ["sleep", "600"]
    networks:
      front:
        aliases:
          - gateway
  api:
    image: alpine:3
    command: ["sleep", "600"]
    networks:
      - front
      - back
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_PASSWORD: example
    networks:
      - back

networks:
  front:
  back:
    internal: true

Two forms appear here. A service can list network names (- front), or use a map so each attachment can carry options such as aliases or a fixed ipv4_address. Once you list networks on a service, it is no longer on default unless you list that too.

Now test who can reach whom:

CONSOLE
$ docker compose exec api ping -c1 db
PING db (172.23.0.2): 56 data bytes
64 bytes from 172.23.0.2: seq=0 ttl=64 time=1.251 ms
$ docker compose exec api ping -c1 proxy
PING proxy (172.22.0.2): 56 data bytes
64 bytes from 172.22.0.2: seq=0 ttl=64 time=1.489 ms
$ docker compose exec proxy ping -c1 -W2 db
ping: bad address 'db'
$ docker compose exec api ping -c1 gateway
PING gateway (172.22.0.2): 56 data bytes
  • api sits on both networks, so it reaches both neighbours.
  • proxy is only on front, so it cannot even resolve db. DNS answers only for containers that share a network with the asker.
  • The alias gateway is another name for proxy, valid on the front network only.
TEXT
  internet
     |
 +---------+  front   +---------+  back (internal)  +---------+
 |  proxy  |----------|   api   |-------------------|   db    |
 +---------+          +---------+                   +---------+

internal networks have no way out

internal: true means Docker attaches no route to the outside world. Containers on that network can talk to each other and nothing else:

CONSOLE
$ docker compose exec db ping -c1 -W2 1.1.1.1
PING 1.1.1.1 (1.1.1.1): 56 data bytes
ping: sendto: Network unreachable
$ docker compose exec api ping -c1 -W2 1.1.1.1
64 bytes from 1.1.1.1: seq=0 ttl=63 time=24.393 ms

The database cannot call out (so a compromised database cannot phone home), while api still has internet access through front. This is one of the cheapest hardening steps in Compose; see Container Security Basics for the larger picture. Note that an internal network cannot publish ports either, so never put a service that needs ports: only on an internal network.

Fixed subnets

You rarely need to pick addresses, but when a firewall rule or another system demands it, the ipam block does the job:

YAML
services:
  a:
    image: alpine:3
    networks:
      lan:
        ipv4_address: 10.77.5.10
networks:
  lan:
    ipam:
      config:
        - subnet: 10.77.5.0/24
CONSOLE
$ docker compose exec a sh -c "ip -4 addr show eth0 | grep inet"
    inet 10.77.5.10/24 brd 10.77.5.255 scope global eth0
$ docker network inspect tcd-b9-ip_lan --format '{{(index .IPAM.Config 0).Subnet}} {{(index .IPAM.Config 0).Gateway}}'
10.77.5.0/24 10.77.5.1

Choose a range that does not overlap with your office VPN or LAN, or you will get confusing routing problems (Troubleshooting Networks has the checks).

Prefer service names and aliases to fixed IPs. IPs are a last resort for legacy software that cannot use DNS.

Volumes: where data lives

A container's writable layer disappears with the container (see Container Storage). To keep data you mount a volume. Compose supports the same three mount types as plain Docker, written inside a service's volumes list:

Entry Type Use it for
dbdata:/var/lib/postgresql/data named volume Databases and anything Docker should manage
./site:/site:ro bind mount Source code and config from your project folder
type: tmpfs tmpfs Scratch data that must never touch disk

A name (no slash or dot at the start) is a named volume; a path starting with ./, ../ or / is a bind mount. Named volumes must also be declared under the top-level volumes key:

YAML
name: tcd-b9-vol
services:
  writer:
    image: alpine:3
    command: ["sh", "-c", "echo \"run at $$(date +%s)\" >> /data/log.txt; cat /data/log.txt"]
    volumes:
      - notes:/data
      - type: tmpfs
        target: /scratch
      - type: volume
        source: shared
        target: /shared
        read_only: true

volumes:
  notes:
  shared:
    name: tcd-b9-shared-volume

The list holds a short form (notes:/data) and two long forms (type: tmpfs, type: volume). The long form is more verbose but spells out every option (read_only, bind.create_host_path, tmpfs.size) and is easier to read when several options are needed.

The key behaviour is that the volume outlives the container. Run the stack twice and the second run still sees the first run's line:

CONSOLE
$ docker compose up
writer-1  | run at 1792767059
$ docker compose up
writer-1  | run at 1792767059
writer-1  | run at 1792767062

Two lines the second time: the file survived because notes is a volume. Now see which volumes Compose created:

CONSOLE
$ docker volume ls --filter name=tcd-b9 --format '{{.Name}}'
tcd-b9-shared-volume
tcd-b9-vol_notes

Compose prefixed notes with the project name (tcd-b9-vol_notes), but shared kept the exact name we gave it with name:. Setting name is how you opt out of the prefix, for example when several projects share a volume.

down keeps volumes; down -v deletes them

This is the most important thing in the lesson.

CONSOLE
$ docker compose down
 Container tcd-b9-vol-writer-1 Removed
 Network tcd-b9-vol_default Removed
$ docker volume ls --filter name=tcd-b9 --format '{{.Name}}'
tcd-b9-shared-volume
tcd-b9-vol_notes
$ docker compose down -v
 Volume tcd-b9-shared-volume Removed
 Volume tcd-b9-vol_notes Removed

docker compose down removes containers and networks but keeps volumes, so your database survives a rebuild. Adding -v deletes the volumes declared in the file along with everything in them. There is no undo.

Never put down -v in a habitual alias or a deploy script for a project that holds real data. Use it deliberately, for example to reset a development database.

Bind mounts in Compose

A bind mount maps a folder from your machine into the container. Relative paths are resolved against the Compose file, which makes the project portable:

YAML
    volumes:
      - ./site:/site:ro

Our test with a read-only mount behaved like this:

CONSOLE
$ docker compose exec app sh -c 'cat /site/index.txt; touch /site/x'
hi
touch: /site/x: Read-only file system

The :ro suffix stops the container from changing your files, which is a good default for config and static content. Development workflows that rely on bind mounts (live reload, watching files) get their own lesson: Compose for Development. Permissions on Linux hosts are covered in Users and Permissions.

External networks and volumes

Sometimes a network or volume is created outside of this Compose project: by another project, by a script, or by hand. Mark it external: true and Compose will use it but never create or delete it:

YAML
name: tcd-b9-ext
services:
  app:
    image: alpine:3
    command: ["sleep", "600"]
    volumes:
      - keep:/keep
networks:
  default:
    name: tcd-b9-shared-net
    external: true
volumes:
  keep:
    external: true
    name: tcd-b9-keepvol

If the resource does not exist yet, Compose refuses to start:

CONSOLE
$ docker compose up -d
network tcd-b9-shared-net declared as external, but could not be found

After creating them with docker network create tcd-b9-shared-net and docker volume create tcd-b9-keepvol, the project starts. And down -v leaves them alone:

CONSOLE
$ docker compose down -v
 Container tcd-b9-ext-app-1 Removed
$ docker network ls --filter name=tcd-b9-shared-net --format '{{.Name}}'
tcd-b9-shared-net
$ docker volume ls --filter name=tcd-b9-keepvol --format '{{.Name}}'
tcd-b9-keepvol

Note the trick on the default network: redefining it with external: true and a name: makes every service join a network shared with other projects. A common use is a shared reverse proxy network, which you will build in Project: Multiple Apps Behind a Proxy.

Choosing a design

  • One small app: do nothing. The default network and one or two named volumes are enough.
  • Public service plus database: two networks, with the database on an internal one.
  • Several projects behind one proxy: an external shared network, plus a private default network per project.
  • Production databases: a named volume, backed up regularly (Backup and Restore). Never rely on the container's writable layer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Compose file has three services and no networks key. What does Compose do?

    Compose creates a single default user-defined bridge, so every service can reach every other by its service name.
  2. 2. db is only on the back network, and proxy is only on front. What happens when proxy pings db?

    Docker's embedded DNS only answers for containers that share a network with the asker, so the lookup fails with bad address 'db'.
  3. 3. What does internal: true on a network do?

    An internal network has no gateway to the outside world, so outbound pings fail with Network unreachable. Published ports do not work on it either.
  4. 4. You run docker compose down on a stack with a named volume dbdata. What happens to the volume?

    down removes containers and networks only. The -v flag also deletes the volumes declared in the file.
  5. 5. A volume is declared with external: true. What does docker compose down -v do to it?

    External resources are managed outside the project. Compose will use them but never create or remove them.

Summary

  • Compose creates a <project>_default bridge network automatically; services reach each other by service name and container port.
  • Use several networks to separate tiers; a service only resolves names on networks it shares, and internal: true cuts off outside access.
  • Named volumes are declared under top-level volumes, are prefixed with the project name unless you set name:, and survive docker compose down.
  • docker compose down -v deletes declared volumes and their data permanently.
  • Bind mounts (./path:/target, optionally :ro) share project files; tmpfs keeps scratch data in memory.
  • external: true tells Compose to use an existing network or volume and never remove it.

Next: Environment, Variables and Secrets