How to Use Networks in Docker Compose: Simple Guide
In
docker-compose.yml, you define networks under the networks key and assign them to services using the networks property. This lets containers communicate on isolated or shared networks, improving organization and security.Syntax
The networks section defines custom networks. Each service can specify which networks it connects to under its networks key. You can set network driver options if needed.
Basic parts:
networks:top-level key to declare networks.service_name:underservices, lists networks the service uses.- Optional network config like
driverto choose network type.
yaml
version: '3.8'
services:
app:
image: alpine
networks:
- mynet
networks:
mynet:
driver: bridgeExample
This example shows two services connected to the same custom network called mynet. They can communicate by container name.
yaml
version: '3.8' services: web: image: nginx networks: - mynet app: image: alpine command: ping -c 3 web networks: - mynet networks: mynet: driver: bridge
Output
PING web (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.123 ms
64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.110 ms
64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.105 ms
--- web ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
Common Pitfalls
Common mistakes include:
- Not defining the network under
networksbut trying to use it in services. - Forgetting to connect all services that need to communicate to the same network.
- Using default networks unintentionally, which can cause isolation issues.
Always explicitly define and assign networks for clear container communication.
yaml
version: '3.8' services: app: image: alpine networks: - mynet db: image: mysql # Missing networks key here networks: mynet: driver: bridge # Corrected version: version: '3.8' services: app: image: alpine networks: - mynet db: image: mysql networks: - mynet networks: mynet: driver: bridge
Quick Reference
| Key | Description |
|---|---|
| networks: | Top-level key to define custom networks |
| service_name.networks: | List of networks a service connects to |
| driver: | Network driver type, e.g., bridge, overlay |
| aliases: | Optional alternative names for containers on the network |
| external: | Use an existing external network instead of creating one |
Key Takeaways
Define custom networks under the top-level 'networks' key in docker-compose.yml.
Assign networks to services using the 'networks' property to enable container communication.
Use the 'driver' option to specify network type like 'bridge' or 'overlay'.
Always connect all communicating services to the same network explicitly.
Avoid relying on default networks to prevent unexpected isolation or conflicts.