Spring Boot+Docker环境下无法连接Eureka Server求助
核心问题
错误日志里的Connection refused是因为容器内的localhost指向容器自身,而非宿主机或Eureka Server容器。你的业务服务容器尝试访问http://localhost:8761时,实际是在访问容器内部的8761端口,而Eureka Server运行在另一个独立容器中,自然连接失败。
具体修复步骤
1. 修正业务服务的Eureka注册地址
在业务服务的**application-docker.properties**(因为你指定了SPRING_PROFILES_ACTIVE: docker,必须用对应profile的配置文件)中,将Eureka地址改为docker-compose中Eureka服务的名称eureka-server:
spring.application.name=aa-service # 关键修改:用服务名替代localhost eureka.client.service-url.defaultZone=http://eureka-server:8761/eureka/ eureka.client.register-with-eureka=true eureka.client.fetch-registry=true eureka.instance.prefer-ip-address=true
注:docker-compose的同一网络(这里是
spring网络)中,容器可以直接通过服务名互相访问,不需要映射端口。
2. 确保Eureka Server的配置适配Docker环境
Eureka Server的application-docker.properties(同样对应docker profile)可以保持基础配置,但建议显式声明绑定地址,避免容器内部访问问题:
spring.application.name=eureka-server server.port=8761 server.address=0.0.0.0 # 允许容器外部/内部访问 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false
3. 调整docker-compose的启动依赖(可选但推荐)
虽然depends_on能保证启动顺序,但不会等待Eureka Server完全就绪。可以给Eureka Server添加健康检查,确保业务服务在Eureka就绪后再启动:
eureka-server: container_name: eurekaserver build: dockerfile: ./docker/eurekaserver.Dockerfile environment: SPRING_PROFILES_ACTIVE: docker ports: - "8761:8761" networks: - spring healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8761/actuator/health"] interval: 10s timeout: 5s retries: 5 restart: unless-stopped aaservice: # ... 其他配置不变 depends_on: - postgres - eureka-server restart: unless-stopped
注:需要给Eureka Server添加
spring-boot-starter-actuator依赖才能使用健康检查端点。
4. 验证Spring Cloud版本兼容性
Spring Boot 3.0对应的Spring Cloud版本是2022.0.x(Kilburn),你的eureka-client:4.0.0是匹配的,但要确保Eureka Server的依赖也使用同版本:
// Eureka Server的依赖 implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server:4.0.0'
验证方法
- 启动所有容器后,访问
http://localhost:8761,查看Eureka控制台是否能看到aa-service和order-service注册成功。 - 查看业务服务的日志,确认不再出现
Connection refused错误。
内容的提问来源于stack exchange,提问作者Nguyễn Đình Khoa

