Search code examples
dockermicroservices

How can one Docker Container find the IP address of another Docker Container?


Working on my first MSA application, and trying to figure out how a Docker container can find the IP address of another Docker Container? My containers know the name of the other container it needs to connect to, but that is it. I can't use a "--link" option or docker-compose as the components can come an go at different times, and I need a programmatic way to find the IP address of the other containers and start connections to them.

I have to think this problem has already been solved long long ago, but my GoogleFoo must be very weak today, as I can't find anything!

Thanks for your help! :)

AAR: So the issue is that on the default 'bridge' bridge network, the Docker DNS does NOT keep track of container names...all other network types it will.

So the accepted solution below is to use any other network and have the containers use that network.

I created another bridge network so that I can still do testing/dev work, and my containers can find one another by name now. For production, I will have to change the network to something like a 'macvlan' type.

If you are using something like Kubernetes, then you will need a Service Discovery solution like Zookeeper or Consul.


Solution

  • You have to define network in your docker-compose as below

    networks:
      my-network:
    

    And then make both the containers part of the same network.

    networks:
      - my-network
    

    And they can access other docker service port using docker service name.

    EDIT 2: Without dokcer-compose I am able to communicate 2 containers as below:

    1) Created netwrok - my-netwrok

    docker network create -d bridge my-network
    

    2) Started 2 service unders same network

    docker run -d --name eureka --network=my-network eureka-service:1.0
    docker run -d --name facility --network=my-network facility-service:1.0
    

    3) Logged in to facility container

    docker exec -it facility bash
    

    4) pinged eureka from inside facility container

    bash-4.4# ping eureka
    PING eureka (172.18.0.2): 56 data bytes
    64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.149 ms
    64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.078 ms