Docker Compose — Custom Networks
Custom networks let you isolate groups of services so they can only communicate with the right peers.
Why Custom Networks?
┌──────────────────────────────────────────┐
│ Compose Project │
│ │
│ ┌── frontend-net ──┐ │
│ │ ┌─────┐ ┌─────┐ │ │
│ │ │ web │ │ api │ │ │
│ │ └─────┘ └──┬──┘ │ │
│ └─────────────┼────┘ │
│ │ │
│ ┌── backend-net ───┐ │
│ │ ┌─────┐ ┌──┴──┐ │ │
│ │ │ db │ │ api │ │ │
│ │ └─────┘ └─────┘ │ │
│ └──────────────────┘ │
│ │
│ web ✗ db (different networks) │
│ api ✓ db (share backend-net) │
└──────────────────────────────────────────┘
Defining Custom Networks
services:
web:
image: nginx:alpine
networks:
- frontend
api:
image: node:20-alpine
networks:
- frontend
- backend
db:
image: postgres:16
networks:
- backend
networks:
frontend:
backend:
Verify Isolation
docker compose up -d
docker compose exec web ping db
ping: bad address 'db' # web cannot reach db — different networks!
docker compose exec api ping db
PING db (172.21.0.2): 56 data bytes
64 bytes from 172.21.0.2: seq=0 ttl=64 time=0.098 ms # api CAN reach db
Network Options
networks:
frontend:
driver: bridge
driver_opts:
com.docker.network.bridge.name: br-frontend
ipam:
config:
- subnet: 172.28.0.0/16
backend:
internal: true # No external internet access
| Option | Purpose |
|---|---|
driver |
Network driver (bridge, overlay, etc.) |
driver_opts |
Driver-specific options |
internal: true |
Block outbound internet access |
ipam |
Custom IP address management |
Listing Networks
docker network ls | grep myapp
NETWORK ID NAME DRIVER SCOPE
a1b2c3d4e5f6 myapp_frontend bridge local
f6e5d4c3b2a1 myapp_backend bridge local
Summary
| Feature | Default Network | Custom Network |
|---|---|---|
| Auto-created | Yes | No (you define them) |
| Isolation | All services together | Fine-grained control |
| Internal mode | No | Supported |
| Custom IPAM | No | Supported |
Quick Reference
| Item | Detail |
|---|---|
| Define | Top-level networks: key |
| Assign | services. |
| Isolation | Services only talk on shared networks |
| Internal | internal: true blocks internet |
| IPAM | Custom subnets via ipam.config |