Search code examples
dockerdocker-composedocker-network

How a container live in two networks can find each network's container with a same name


By "each network's container with a same name", I mean a scenario like this:

There are two networks, called one and two. In one, there is a container called server, and in two there is also a container called server. Now, if another container joins both one and two networks, how can it tell the two server containers apart?

This can be demonstrated with two docker-compose.yml files:

#server.yml

version: '3.7'
services:
  server:
    image: toolbelt/netcat
    entrypoint: nc -kl 1111

and

#client.yml

version: '3.7'
services:
  client:
    image: toolbelt/netcat
    networks:
      - one
      - two
    entrypoint:
      - sh
      - -c
      - echo abc | nc -q 1 server 1111

networks:
  one:
    external:
      name: one_default
  two:
    external:
      name: two_default

We can start the two servers with

docker-compose -p one -f server.yml up
docker-compose -p two -f server.yml up

and ask the client to connect with

docker-compose -p client -f client.yml up

And currently, only the server in network one echos abc, which means server in network two is shadowed.

I wonder how I can make the client be able to access both servers?

I'm aware of the network alias feature, where I can give each server a additional name in their own network, so if I make them unique, I can ask the client to access both. But in my real case, I have no permission to change server.yml.

Is it possible to somehow give servers alias names in client's docker-compose.yml file or are there some other ways to tell the two servers apart?


Solution

  • you can connect to the distinct service via:

    [container name].[project]_[network name]
    

    For example

    • your service is called "server"
    • your project is called "one"
    • your network in project "one" is called "default" (if none is specified default is used)

      ping server.one_default