Communication between two microservices by Docker hostname

╄→гoц情女王★ 提交于 2019-12-12 15:55:36

问题


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:


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



来源:https://stackoverflow.com/questions/49534740/communication-between-two-microservices-by-docker-hostname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!