dockerdocker-compose

Docker-Compose, using multiple networks with include


I have a microservice architecture with a repo for the frontend and another for the backend

I want to split the docker composes for clarity but have 1 main compose to group them up when building tests for consistency. So i am using include in conjunction with networks

I am trying to split my docker compose into 2 compose files: for example:

#front/docker-compose.yaml

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: web
    ports:
      - "80:80"
    networks:
      - project_gateway

networks:
  project_gateway:
    external: true

#back/docker-compose.yaml

services:
  gateway_service:
    build:
      context: ./gatewayService
      dockerfile: Dockerfile
    container_name: gateway_service
    ports:
      - "8000:8000"
    networks:
      - project_backend
      - project_gateway

  service_1:
    build:
      context: ./service_1
      dockerfile: Dockerfile
    container_name: service_1
    ports:
      - "8001:8001"
    networks:
      - project_backend
networks:
  project_backend:
    external: true
  project_gateway:
    external: true

and outside: #./docker-compose.yaml

networks:
  backend:
    driver: bridge
  gateway:
    driver: bridge


include:
  - back/docker-compose.yaml
  - front/docker-compose.yaml

Solution

  • For most practical purposes, you don't need multiple networks:. Compose provides a network named default for you and automatically attaches containers to it; also see Networking in Compose in the Docker documentation.

    (Also consider, on the one hand, that your home environment probably doesn't have a separate network router and IPv4 block for the printer, and for each computer, and for the smart TV; and on the other, that the generally more production-oriented Kubernetes setup doesn't support multiple networks at all.)

    This means you typically want to delete all of the networks: blocks, everywhere they exist, both in the top level and in the individual services. You also do not need to override container_name: in ordinary use, since the Compose service names are already usable as host names.

    This would reduce the two Compose files to just

    # front/docker-compose.yml
    version: '3.8'
    services:
      web:
        build: .
        ports:
          - "80:80"
    
    # back/docker-compose.yml
    version: '3.8'
    services:
      gateway_service:
        build: ./gatewayService
        ports:
          - "8000:8000"
     service_1:
        build: ./service_1
        ports:
          - "8001:8001"
    

    Since you're not trying to merge incompatible networks:, your top-level Compose file can then just include: the two separate files.

    # ./docker-compose.yml
    version: '4.0+compose-tool-2.20'
    include:
      - front/docker-compose.yml
      - back/docker-compose.yml