9.2.2 Compose Networks
A focused guide to Compose Networks, connecting core concepts with practical Docker and container operations.
The top-level networks key in a Compose file declares any networks the application's services need beyond the automatically created default, giving explicit control over network topology when an application's structure calls for something more deliberate than a single shared network.
Declaring a Network
A network is declared by name under the top-level networks key, then referenced by services that should be attached to it.
services:
api:
networks:
- backend-net
db:
networks:
- backend-net
networks:
backend-net:
Why Explicit Network Declaration Is Sometimes Necessary
Without any explicit declaration, Compose's automatically created default network already connects every service together — explicit networks become necessary specifically when an application needs more deliberate segmentation than this single, shared network provides.
services:
frontend:
networks:
- public-net
api:
networks:
- public-net
- private-net
db:
networks:
- private-net
networks:
public-net:
private-net:
Here, frontend can reach api over public-net, but cannot directly reach db, since they share no common network — only api, attached to both, bridges the two segments.
Configuring a Declared Network's Driver and Options
A declared network can specify its driver and other options, just as a network created directly with docker network create could.
networks:
backend-net:
driver: bridge
driver_opts:
com.docker.network.bridge.name: backend0
Inspecting the Networks Compose Actually Creates
Confirming exactly what networks Compose created on the application's behalf validates that the declared configuration is taking effect as expected.
docker network ls
docker network inspect myapp_backend-net
Why the Networks Key Matters
Explicitly declaring networks provides the control needed to express deliberate network segmentation within a Compose application, a capability that becomes important as an application's services grow more numerous and their communication patterns more deliberately structured.