'docker-compose networking multiple apps with same service name

Problem:

When having two docker-compose files / projects with the same services, under the same network, when you spin up t he second compose project, the DNS name for the service gets overwritten.

eg:

App 1

version: "3.1"
services:
  db:
    image: mysql:8.0
    container_name: monolith-db
    networks:
      - my-network-name

  webserver:
    image: nginx:alpine
    container_name: monolith-webserver
    networks:
      - my-network-name

  phpfpm:
    container_name: monolith-phpfpm
    networks:
      - my-network-name
networks:
  my-network-name:
    external: true

App 2

version: "3.1"
services:
  db:
    image: mysql:8.0
    container_name: ms-auth-db
    networks:
      - my-network-name

  webserver:
    image: nginx:alpine
    container_name: ms-auth-webserver
    networks:
      - my-network-name

  phpfpm:
    container_name: ms-auth-phpfpm
    networks:
      - my-network-name
networks:
  my-network-name:
    external: true

If you start App 1, the services inside can connect to their declared services by service name as hostname, for example, in my config I have database-host: db However, when I do docker-compose -p ms-auth --env-file .env -f infra/local/docker-compose.yml up -d then db hostname now points to App 2's db service.



Solution 1:[1]

The solution is to use the container_name as hostname

e.g. instead of connecting to db, configure App 1' config files to use the hostname monolith-db, and for pointing from App 1 to App 2, also use container name as hostname, e.g. ms-auth-host: ms-auth-webserver

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JorgeeFG