How to use Docker Compose networking?
· Category: Docker
Short answer
Docker Compose automatically creates a default bridge network for each project. Services in the same Compose file can communicate by service name. You can define custom networks for fine-grained isolation and control.
Steps
- Define networks in the
networkssection ofdocker-compose.yml. - Attach services to networks with the
networkskey. - Use service names as hostnames for inter-service communication.
Example
version: "3.9"
services:
web:
image: nginx
networks:
- frontend
api:
image: myapi
networks:
- frontend
- backend
db:
image: postgres
networks:
- backend
networks:
frontend:
backend:
driver: bridge
Tips
- Default network names are prefixed with the project directory name.
- Use
external: trueto attach to an existing network. - IPv6 can be enabled per network with
enable_ipv6: true.
Common issues
- Services cannot communicate if they are on different networks with no shared network.
- DNS resolution uses service names, not container names, in Compose.
- Changing network names can break existing volume or network references.