Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between two microservices by Docker hostname

How it works now:

Microservice X makes REST API request to Microservice Y with static ip

http://{ip-address}:{port}/doSomething

The problem:

The problem is that I can no long guarantee that static ip. I wan't to solve this by using the docker hostname instead:

http://hostname:{port}/doSomething

I tried achieving this by creating a used defined network in docker-compose:

    #part of docker-compose file
    streamapp:
      hostname: twitterstreamapp
      image: twitterstreamapp
      container_name: twitterstreamapp
      restart: always
      ports:
        - '8090:8080'
      build:
        context: ./TwitterStream
        dockerfile: Dockerfile

    storeapp:
      hostname: twitterstoreapp
      image: twitterstoreapp
      container_name: twitterstoreapp
      restart: always
      ports:
        - '8095:8080'
      build:
        context: ./TwitterStore
        dockerfile: Dockerfile
      depends_on:
        - 'mysql-db'
      networks:
        - backend

  volumes:
    MyDataVolume:

  networks:
    backend:
      driver: bridge

I can ping from Container X to Container Y. But not Curl for example. How can I fix this, or is this not the best way to achieve what I want.

like image 914
Quinten Scheppermans Avatar asked Dec 13 '22 17:12

Quinten Scheppermans


1 Answers

The solution is very simple, instead of using IPs or Hostnames you can use the service's name.

In your example, in the streamapp service you can access the other by using http://storeapp:8080.

Similar, in the storeapp service you can access the other at http://streamapp:8080.

Please not that you must use the internal ports, not the exported ones.

This does not apply when you access the service from the other machines, i.e. from the internet. In that case you must use the form http://{IP_OF_THE_MACHINE}:8090

like image 54
Constantin Galbenu Avatar answered May 08 '23 10:05

Constantin Galbenu