You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker构建主应用容器无法连接Spring Cloud配置服务器问题排查

问题:Docker构建阶段无法访问宿主机上的Spring Cloud Config服务器

我有两个容器化应用部署在同一服务器:一个是提供各类application.properties文件的Spring Cloud Config服务器,另一个是通过它拉取配置的主应用。流水线包含测试与部署任务,测试任务中用docker build构建主应用镜像时,Dockerfile里的RUN mvn clean install -Dspring.profiles.active=$profil命令超时,无法访问Config服务器地址,但本地执行docker build却能正常连接。推测是构建中的容器无法和宿主机通信,想在不用docker-compose的前提下解决这个问题。


可复现的最小配置

配置服务器

application.yaml

server:
   port: 9101
spring:
  application:
    name: config-server
  cloud:
    compatibility-verifier:
     enabled: false
    config:
      server:
       encrypt:
          enabled: false
       git:
          clone-on-start: true
          uri: uri repo git 
       ignoreLocalSshSettings: true

主类代码

@SpringBootApplication
@EnableConfigServer
public class ServerConfigApplication {

  public static void main(String[] args) {
    SpringApplication.run(ServerConfigApplication.class, args);
   }

}

主应用

Dockerfile

FROM maven:3.9.4-eclipse-temurin-17-alpine as build
ARG profil=DEV
WORKDIR main-app
COPY . .
RUN echo "Building image with profil : $profil"
RUN mvn clean install -Dspring.profiles.active=$profil

FROM eclipse-temurin:17-alpine
WORKDIR app
COPY --from=build /main-app/target/app-0.0.1-SNAPSHOT.jar .
EXPOSE 8082
ENTRYPOINT ["java", "-jar", "app-0.0.1-SNAPSHOT.jar"]

bootstrap.properties(配置拉取地址)

spring.cloud.config.uri=http://xxx.xxx.xxx.xxx:9101

解决方案

1. 让构建容器直接访问宿主机的Config服务器

Docker构建阶段的容器默认处于default网络,要打通它和宿主机的通信,有两种直接可行的方式:

方式一:使用Docker内置的宿主机DNS(推荐)

Linux环境下Docker 20.10+版本提供了host.docker.internal这个特殊DNS名称,可直接指向宿主机。

  • 修改主应用的bootstrap.properties:
    spring.cloud.config.uri=http://host.docker.internal:9101
    
  • 执行构建命令时添加--add-host参数:
    docker build --build-arg profil=DEV --add-host host.docker.internal:host-gateway -t main-app .
    

方式二:指定宿主机内网IP

如果host.docker.internal不可用,直接把bootstrap.properties中的IP替换为宿主机的内网IP(比如192.168.1.100):

spring.cloud.config.uri=http://192.168.1.100:9101

同时要确保宿主机防火墙允许9101端口的入站请求。

2. 重构构建流程(可选)

如果不想在构建阶段依赖外部服务,可以把配置拉取步骤移到容器启动阶段:

  • 修改Dockerfile,让mvn clean install只完成编译打包,跳过配置拉取环节(比如调整Maven插件或Spring配置)
  • 在容器启动的ENTRYPOINT中添加配置拉取逻辑,或者启用Spring Cloud的延迟加载配置功能
    这样构建阶段不再依赖Config服务器,彻底避免构建时的网络问题。

内容的提问来源于stack exchange,提问作者Maurel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:15:06