Docker Compose启动Spring微服务失败:Config Server正常业务服务异常
问题描述
基于Spring Boot搭建的微服务架构包含Config Server、Post Service、User Service三个服务,使用Docker Compose部署时,Config Server可正常启动,但Post Service和User Service启动失败。
关键配置与日志
Docker Compose核心配置片段
userservice: image: example/userservice environment: CONFIG_SERVER: http://configserver:8071 # 其他环境变量省略 depends_on: configserver: condition: service_healthy # 其他配置省略 configserver: image: example/configserver ports: - "8071:8071" healthcheck: test: "curl --fail --silent http://localhost:8071/actuator/health/readiness | grep UP || exit 1" # 其他配置省略
User Service的application.yml
spring: application: name: userservice config: import: "configserver:${CONFIG_SERVER:http://localhost:8071/}"
启动错误日志片段
userservice | 2024-08-05T07:32:22.288Z INFO 1 --- [userservice] [ restartedMain] o.s.c.c.c.ConfigServerConfigDataLoader : Fetching config from server at : http://localhost:8071/ userservice | 2024-08-05T07:32:22.289Z INFO 1 --- [userservice] [ restartedMain] o.s.c.c.c.ConfigServerConfigDataLoader : Exception on Url - http://localhost:8071/:org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:8071/userservice/default": Connection refused. userservice | 2024-08-05T07:32:22.393Z ERROR 1 --- [userservice] [ restartedMain] o.s.boot.SpringApplication : Application run failed userservice | userservice | org.springframework.cloud.config.client.ConfigClientFailFastException: Could not locate PropertySource and the resource is not optional, failing
日志显示服务尝试连接默认地址http://localhost:8071,而非环境变量配置的http://configserver:8071。
排查与解决方案
1. 验证环境变量是否传递到容器
先确认Docker Compose的环境变量是否正确传入服务容器:
# 进入User Service容器 docker exec -it userservice sh # 查看环境变量值 echo $CONFIG_SERVER
- 如果输出不是
http://configserver:8071,检查docker-compose.yml的缩进(YAML对缩进敏感)或环境变量名拼写。 - 如果输出正确,说明问题出在Spring Boot的配置加载逻辑。
2. 启用Bootstrap上下文(核心解决办法)
Spring Boot 2.4+默认禁用了Bootstrap上下文,而Spring Cloud Config Client需要在Bootstrap阶段加载环境变量来获取Config Server地址。解决步骤:
- 在User/Post Service的依赖中添加
spring-cloud-starter-bootstrap:
Maven(pom.xml)
Gradle(build.gradle)<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bootstrap</artifactId> </dependency>implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap' - 重新构建服务镜像,然后重启Docker Compose。
3. 验证Config Server的健康检查与可用性
确认Config Server确实处于健康可用状态:
# 进入Config Server容器 docker exec -it configserver sh # 调用健康检查端点 curl http://localhost:8071/actuator/health/readiness
- 如果返回内容不包含
"status":"UP",检查Config Server的application.yml是否正确配置了Actuator端点:management: endpoints: web: exposure: include: health,readiness endpoint: health: show-details: always
4. 统一Config Server地址格式
将环境变量中的CONFIG_SERVER值改为带末尾斜杠的格式,与application.yml中的默认值保持一致:
# docker-compose.yml中修改 CONFIG_SERVER: http://configserver:8071/
内容的提问来源于stack exchange,提问作者Cody
相关产品推荐
相关产品推荐

