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

  1. Define networks in the networks section of docker-compose.yml.
  2. Attach services to networks with the networks key.
  3. 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: true to 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.