Docker中无法运行注册到Eureka的UserService
相关配置
UserDockerFile代码
FROM openjdk COPY ./target/user_service-0.0.1-SNAPSHOT.jar . ENV EUREKA_INSTANCE_HOSTNAME=host.docker.internal CMD ["java","-jar","user_service-0.0.1-SNAPSHOT.jar"]
用户服务application.yaml配置
server: port: 9001 spring: application: name: user-service eureka: instance: hostname: localhost
Eureka Server的application.yaml配置
server: port: 8761 eureka: client: registerWithEureka: false fetchRegistry: false server: waitTimeInMsWhenSyncEmpty: 0 instance: prefer-ip-address : true
执行的镜像构建及运行命令
docker run -it -p 9001:9001 user-service
错误信息
Request execution error. endpoint=DefaultEndpoint{ serviceUrl='http://localhost:8761/eureka/},
exception=I/O error on GET request for "http://localhost:8761/eureka/apps/": Connect to
localhost:8761 [localhost/127.0.0.1] failed: Connection refused; nested exception is
org.apache.http.conn.HttpHostConnectException: Connect to localhost:8761 [localhost/127.0.0.1]
failed: Connection refused stacktrace=org.springframework.web.client.ResourceAccessException:
I/O error on GET request for "http://localhost:8761/eureka/apps/": Connect to localhost:8761
[localhost/127.0.0.1] failed: Connection refused; nested exception is
org.apache.http.conn.HttpHostConnectException: Connect to localhost:8761 [localhost/127.0.0.1]
failed: Connection refused
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
解决方案
核心问题是Docker容器内的localhost指向容器自身,而Eureka Server运行在宿主机上,导致容器无法连通Eureka服务。
修改用户服务application.yaml配置:
补充Eureka服务地址配置,将其指向宿主机:server: port: 9001 spring: application: name: user-service eureka: instance: hostname: host.docker.internal # 匹配Dockerfile中的环境变量,适配Windows/macOS环境 client: serviceUrl: defaultZone: http://host.docker.internal:8761/eureka/ # 指定宿主机上的Eureka地址Linux环境适配方案:
如果是Linux系统,host.docker.internal可能无法直接生效,可选择两种方式:- 让容器共享宿主机网络,运行命令改为:
docker run -it --network=host user-service - 替换配置中的
host.docker.internal为宿主机的实际IP地址:eureka: client: serviceUrl: defaultZone: http://宿主机实际IP:8761/eureka/
- 让容器共享宿主机网络,运行命令改为:
内容的提问来源于stack exchange,提问作者amanbisht39

