Search code examples
spring-bootspring-cloudnetflix-eureka

java.net.UnknownHostException during Eureka service discovery


According to this blog https://spring.io/blog/2015/07/14/microservices-with-spring

Was able to run the application without any issues. In this order:

  • java -jar microservice-demo-0.0.1-SNAPSHOT.jar registration 1111
  • java -jar microservice-demo-0.0.1-SNAPSHOT.jar accounts 2222
  • java -jar microservice-demo-0.0.1-SNAPSHOT.jar web 3333

But when trying to hit any service through the web application (http://localhost:3333/) which uses the http://ACCOUNTS-SERVICE url to access any accounts service endpoints like http://ACCOUNTS-SERVICE/accounts/123456789 I'm getting an error response:

Response Status: 500 (Internal Server Error)
Cause: org.springframework.web.client.ResourceAccessException I/O error on GET request for "http://ACCOUNTS-SERVICE/accounts/123456789": ACCOUNTS-SERVICE; nested exception is java.net.UnknownHostException: ACCOUNTS-SERVICE

When I provide the real address (http://localhost:2223/) of the accounts service to the web server instead of the http://ACCOUNTS-SERVICE everything works properly but there is no service discovery in this case.

The source code is stored at: https://github.com/paulc4/microservices-demo


Solution

  • This issue was due to the RestTemplate was no longer auto-created in the Brixton release-train (Spring Cloud 1.1.0.RELEASE), so the RestTemplate could not resolve properly the http://ACCOUNTS-SERVICE url using the service discovery server.

    Was able to fix this issue after declaring a RestTemplate bean with @LoadBalanced as follows:

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }