Spring Boot微服务Docker Compose部署报错:TransportException无法请求服务器
Spring Boot微服务Docker-Compose配置问题:Eureka与Gateway无法连接服务
Config Server运行正常,但Eureka Server和API Gateway抛出错误:com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
各服务Docker-Compose代码片段
Config Server
configserver: image: configserver container_name: configServer build: context: ./configserver dockerfile: Dockerfile environment: CONFIGSERVER_URI: "http://localhost:9191" CONFIGSERVER_PORT: "9191" ports: - "9191:9191" networks: backend: aliases: - "configserver"
Eureka Server
eurekaserver: image: eurekaserver ports: - "8761:8761" build: context: ./discoveryserver dockerfile: Dockerfile environment: CONFIGSERVER_URI: "http://localhost:9191" CONFIGSERVER_PORT: "9191" EUREKASERVER_URI: "http://localhost:8761/eureka/" EUREKASERVER_PORT: "8761" depends_on: configserver: condition: service_started networks: backend: aliases: - "eurekaserver"
API Gateway
gatewayserver: image: gatewayserver ports: - "8600:8600" build: context: ./api-gateway dockerfile: Dockerfile environment: PROFILE: "default" SERVER_PORT: "8600" CONFIGSERVER_URI: "http://localhost:9191" EUREKASERVER_URI: "http://localhost:8761/eureka/" EUREKASERVER_PORT: "8761" CONFIGSERVER_PORT: "9191" depends_on: configserver: condition: service_started eurekaserver: condition: service_started networks: backend: aliases: - "gateway"
问题原因
容器内的localhost指向容器自身,而非宿主机或其他容器。当前配置中Eureka和Gateway用localhost访问Config Server、Gateway用localhost访问Eureka,导致跨容器请求失败。
解决方案
1. 替换容器间访问地址为服务别名/服务名
将环境变量中的localhost替换为docker-compose中定义的服务别名(或服务名):
- Config Server的访问地址改为
http://configserver:9191 - Eureka Server的访问地址改为
http://eurekaserver:8761/eureka/
修改后的Eureka Server环境变量:
environment: CONFIGSERVER_URI: "http://configserver:9191" CONFIGSERVER_PORT: "9191" EUREKASERVER_URI: "http://eurekaserver:8761/eureka/" EUREKASERVER_PORT: "8761"
修改后的API Gateway环境变量:
environment: PROFILE: "default" SERVER_PORT: "8600" CONFIGSERVER_URI: "http://configserver:9191" EUREKASERVER_URI: "http://eurekaserver:8761/eureka/" EUREKASERVER_PORT: "8761" CONFIGSERVER_PORT: "9191"
2. 添加健康检查确保服务就绪
depends_on的service_started仅保证容器启动,不保证服务完全就绪。添加健康检查,确保依赖服务可用后再启动当前服务:
给Config Server添加健康检查:
configserver: # ...其他配置 healthcheck: test: ["CMD", "curl", "-f", "http://localhost:9191/actuator/health"] interval: 10s timeout: 5s retries: 5
给Eureka Server添加健康检查,并修改依赖条件:
eurekaserver: # ...其他配置 healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8761/actuator/health"] interval: 10s timeout: 5s retries: 5 depends_on: configserver: condition: service_healthy
修改Gateway的依赖条件:
gatewayserver: # ...其他配置 depends_on: configserver: condition: service_healthy eurekaserver: condition: service_healthy
注意:需确保各服务已引入Spring Boot Actuator依赖,并开启健康端点。
内容的提问来源于stack exchange,提问作者Sercan Noyan Germiyanoğlu
相关产品推荐
相关产品推荐

