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

GitLab CI/CD集成SonarQube遇连接拒绝问题求助

GitLab CI/CD集成SonarQube时连接拒绝问题排查与解决

错误信息

[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar (default-cli) on project user_ingredient_service: Unable to execute SonarScanner analysis: Fail to get bootstrap index from server: Failed to connect to /127.0.0.1:9000: Connection refused -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar (default-cli) on project user_ingredient_service

问题背景

已在GitLab变量中配置SONAR_HOST_URL和SONAR_TOKEN,本地浏览器可正常访问localhost:9000的SonarQube服务,但GitLab CI/CD执行Maven Sonar插件时出现连接拒绝错误。

核心原因分析

  1. 网络寻址错误:CI运行的容器内localhost指向容器自身,而非宿主机的SonarQube服务
  2. 变量传递失效:GitLab变量未正确传递到CI任务,或SONAR_HOST_URL配置仍为localhost:9000
  3. Runner网络限制:GitLab Runner容器的网络模式无法访问宿主机的SonarQube服务
  4. SonarQube监听限制:SonarQube仅绑定127.0.0.1,拒绝外部容器访问

解决方案

1. 修正SONAR_HOST_URL为宿主机可访问地址

将GitLab变量SONAR_HOST_URL从http://localhost:9000修改为以下任一有效地址:

  • 宿主机的实际IP地址(例如http://192.168.1.100:9000)
  • 使用Docker特殊DNS名称:
    • Windows/macOS Docker Desktop:直接使用http://host.docker.internal:9000
    • Linux环境:需先给Runner添加host映射,在Runner启动命令中添加--add-host=host.docker.internal:host-gateway,或修改config.toml:
      [runners.docker]
        extra_hosts = ["host.docker.internal:host-gateway"]
      

2. 验证GitLab变量传递有效性

在sonarqube-check任务的script开头添加调试命令,确认变量是否正确加载:

sonarqube-check:
  # 原有配置...
  script:
    - echo "SONAR_HOST_URL: $SONAR_HOST_URL"
    - echo "SONAR_TOKEN: $SONAR_TOKEN"
    - mvn $MAVEN_CLI_OPTS verify sonar:sonar -Dsonar.qualitygate.wait=true -DskipTests

确保变量为项目/组级可见,未设置为"Protected"(除非运行分支为受保护分支)。

3. 调整GitLab Runner网络模式

如果SonarQube与Runner在同一宿主机,可将Runner的Docker executor设为host网络模式(注意:该模式会让容器共享宿主机网络,按需使用):
修改config.toml:

[[runners]]
  # 原有配置...
  [runners.docker]
    network_mode = "host"

重启Runner生效:docker restart gitlab-runner

4. 确保SonarQube监听所有地址

修改SonarQube的Docker Compose配置,添加SONAR_WEB_HOST=0.0.0.0环境变量,让服务监听所有网卡:

sonarqube:
  image: sonarqube
  container_name: sonarqube
  environment:
    SONAR_ES_BOOTSTRAP_CHECKS_DISABLE: true
    SONAR_JDBC_USERNAME: sonartest
    SONAR_JDBC_PASSWORD: sonartest
    SONAR_JDBC_URL: jdbc:postgresql://db:5432/postgres
    SONAR_WEB_HOST: 0.0.0.0  # 添加此行
  # 原有端口、卷配置...

重启SonarQube:docker-compose down && docker-compose up -d


验证步骤

在CI任务中添加连通性测试命令,确认网络可达:

sonarqube-check:
  script:
    - curl -v $SONAR_HOST_URL/api/system/status
    - mvn $MAVEN_CLI_OPTS verify sonar:sonar -Dsonar.qualitygate.wait=true -DskipTests

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:47:09