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

GitLab流水线中Azure Cosmos DB Testcontainers连接被拒绝问题排查

问题原因及解决方法

可能的原因

  • 端口映射错误或硬写固定地址:Azure Cosmos DB模拟器默认使用8081、10250-10254等端口,但GitLab流水线中Docker容器的端口多为随机映射,直接写127.0.0.1:8081会指向Runner主机而非容器本身。
  • 容器未完全就绪就发起连接:Cosmos DB模拟器启动初始化耗时比常规数据库长,测试代码在服务未就绪时发起请求,导致连接被拒。
  • GitLab Runner网络/权限限制:
    • Docker-in-Docker环境下存在网络隔离,测试代码无法直接访问容器端口;
    • Runner未配置特权模式,Cosmos DB模拟器需要的共享内存挂载、端口绑定等系统权限不足。
  • 容器启动异常:模拟器容器因资源不足、镜像拉取失败等原因退出,导致端口无服务监听。

对应解决方法

1. 动态获取容器映射端口

修改测试代码,不要硬写localhost:8081,通过Testcontainers API获取容器实际映射端口:

var cosmosContainer = new CosmosDbBuilder()
    .WithImage("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest")
    .WithExposedPorts(8081, 10250, 10251, 10252, 10253, 10254)
    .Build();

await cosmosContainer.StartAsync();

// 获取映射后的8081端口,生成有效连接端点
var mappedPort = cosmosContainer.GetMappedPort(8081);
var cosmosEndpoint = $"http://localhost:{mappedPort}";
// 使用该端点初始化Cosmos客户端

2. 添加容器就绪等待策略

在容器启动后,等待模拟器完全就绪再执行测试,比如监听端口或健康检查端点:

var cosmosContainer = new CosmosDbBuilder()
    .WithImage("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest")
    .WithWaitStrategy(Wait.ForUnixContainer()
        .UntilPortIsAvailable(8081)
        .UntilHttpRequestIsSucceeded(r => r.ForPath("/_explorer/emulator.ping").ForPort(8081)))
    .Build();

3. 调整GitLab CI配置确保网络与权限

更新.gitlab-ci.yml,配置Docker-in-Docker服务并开启特权模式:

services:
  - name: docker:dind
    command: ["--tls=false"]

variables:
  DOCKER_HOST: tcp://docker:2375
  DOCKER_DRIVER: overlay2
  DOCKER_TLS_CERTDIR: ""

test-job:
  stage: test
  image: mcr.microsoft.com/dotnet/sdk:7.0
  before_script:
    - docker info
  script:
    - dotnet test --no-restore
  tags:
    - docker
  privileged: true # 必须开启,Cosmos模拟器需要特权权限才能正常运行

4. 排查容器启动日志

在流水线中添加日志输出,确认模拟器是否正常启动:

// 容器启动后打印日志
var logs = await cosmosContainer.GetLogsAsync();
Console.WriteLine("Cosmos Emulator 启动日志:");
Console.WriteLine(logs.Stdout);
Console.WriteLine(logs.Stderr);

或在GitLab CI脚本中直接查看容器状态:

script:
  - dotnet test --no-restore
  - docker ps -a # 查看所有容器运行状态
  - docker logs $(docker ps -q --filter ancestor=mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator) # 打印模拟器容器日志

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:32:41