Docker容器上Spring Cloud微服务相互调用时报错:java.net.UnknownHostException:主机名 解决方案

项目背景:
采用Spring Cloud+IDEA+Maven搭建了由多个微服务组成的项目,部署上线是用的是Docker容器技术。

问题描述:
各个项目在本地启动测试时,各个微服务都正常调用,而且都注册到了eureka注册中心,但是当项目部署到docker容器上之后(一个项目一个容器),相互调用时报java.net.UnknownHostException:主机名的错误。
Docker容器上Spring Cloud微服务相互调用时报错:java.net.UnknownHostException:主机名 解决方案_第1张图片
项目配置文件如下所示:

server:
  port: 8081
eureka:
  client:
    service-url:
      defaultZone: http://root:[email protected]:7776/eureka
  instance:
    lease-expiration-duration-in-seconds: 2
    lease-renewal-interval-in-seconds: 2
    instance-id: ${spring.cloud.client.ipAddress}:${server.port}
spring:
  application:
    name: eureka-provider-demo

解决方案:
将每个需要注册的微服务的application.yml文件中添加一行:prefer-ip-address: true
改后如下所示:

server:
  port: 8081
eureka:
  client:
    service-url:
      defaultZone: http://root:[email protected]:7776/eureka
  instance:
    lease-expiration-duration-in-seconds: 2
    lease-renewal-interval-in-seconds: 2
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ipAddress}:${server.port}
spring:
  application:
    name: eureka-provider-demo

此时调用就恢复正常了

你可能感兴趣的:(eureka,spring,boot,docker)