Call Microservice from another Microservice within Docker

柔情痞子 提交于 2020-01-14 02:50:06

问题


I created several Microservices in C# that are running on docker in windows, I need to call Microservice from another Microservice so I used this way to call:

    [HttpGet("GetOrder/{Object_ID}")]
    public Order GetOrder (int id)
    {
        string Baseurl = "http://189.29.0.100/";
        …..

        using (var client = new HttpClient())
        {
            //Passing service base url  
            client.BaseAddress = new Uri(Baseurl);

            client.DefaultRequestHeaders.Clear();
            //Define request data format  
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
            borrowerData = await client.GetStringAsync("api/order/" + Id.ToString());

        }

       …
    }

I used the fix IP in Composed file as follows:

 orderservice:
    environment:
     - ASPNETCORE_ENVIRONMENT=Development
   ports:
  - "80"
networks:
  default:
    ipv4_address: 189.29.0.100

The problem is when we deploy this project in VM, how to make it work with these Ips?


回答1:


Docker compose create a virtual network on you host and the services are not routable from outside of docker with those IPs. But inside the virtual network all services can access to each other with their names (http://otherservice/). If you want to access to all deployed microservices on VM you will need a reverse proxy inside your docker compose. For example an nginx service that dispatch request to other services.




回答2:


I agree with @Bardia that using a docker-compose file is the easiest way to let microservices know the location of each other! Personally, I also use one compose file for all my microservices.

So if you name the service service-a in your docker-compose.yml file, you will be able to find it by http://service-a:{port}/path. This has a huge advantage: you can use the same port on every microservice without worrying about port collision (since DNS is used to resolve the path), this is also crucial for enabling horizontal scaling!

Going one step further, like @Bardia said, add a reverse-proxy instead of starting real chaos with ports on the host machine... I personally like Traefik, you can configure it by using labels in your service descriptions of the compose file. This also has the advantages for your UI application (if you have one) to access the microservice APIs via relative paths. Thus, you can deploy it anywhere without the necessity to change paths.



来源:https://stackoverflow.com/questions/46370014/call-microservice-from-another-microservice-within-docker

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