Communication between two microservices by Docker

2019-07-04 23:48发布

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.

1条回答
▲ chillily
2楼-- · 2019-07-05 00:45

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

查看更多
登录 后发表回答