无法连接GitHub Actions中Docker部署的Cosmos DB模拟器
问题
在GitHub Actions环境中,通过Docker Compose启动Azure Cosmos DB模拟器后,Node.js项目的Jest集成测试无法连接该实例。本地测试可正常运行,但CI环境中存在以下矛盾现象:
docker ps -a显示容器处于运行状态nc -zv localhost:8081检测到端口已连通- 模拟器日志显示进程反复启动、关闭
- 测试访问
https://localhost:8081时出现超时错误
相关配置
Docker Compose配置
version: '3' services: cosmosdb: restart: always container_name: "azure-cosmosdb-emulator" hostname: "azure.cosmosdb" image: 'mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest' tty: true ports: - '8081:8081' - '10250-10255:10250-10255' environment: AZURE_COSMOS_EMULATOR_PARTITION_COUNT: 10 AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE: "true"
GitHub Actions配置
jobs: run-tests: timeout-minutes: 10 runs-on: ubuntu-latest steps: - name: Check out code uses: actions/checkout with: fetch-depth: 2 - name: Setup Node.js environment uses: actions/setup-node - name: Docker Compose run: | docker compose -f tests/docker-compose.yml up -d - name: Integration test run: | cd tests yarn install --immutable yarn test cd .. - name: Docker Compose run: docker compose -f tests/docker-compose.yml down
原因分析
- 启动时序问题:GitHub Actions中
docker compose up -d后立即执行测试,但Linux版Cosmos DB模拟器启动初始化耗时较长,端口虽已开放但服务未真正就绪,导致连接超时。 - 资源不足触发重启:GitHub Actions的Ubuntu Runner默认资源(CPU/内存)有限,而Cosmos DB模拟器对资源要求较高,资源不足会导致进程崩溃,再通过
restart: always策略反复重启。 - 证书信任缺失:Linux版模拟器使用自签名证书,本地环境通常已手动信任该证书,但CI环境未配置证书信任,导致HTTPS连接被静默拒绝(表现为超时)。
解决方案
1. 等待模拟器就绪后再执行测试
在启动容器后添加轮询逻辑,直到模拟器健康检查端点可访问:
- name: Wait for Cosmos DB Emulator to be ready run: | until curl -k -f https://localhost:8081/_explorer/emulator.pem; do echo "Waiting for Cosmos DB Emulator..." sleep 5 done
注:
-k参数临时跳过证书验证,优先确保服务可访问。
2. 调整资源配置与重启策略
- 移除
restart: always:避免资源不足时无限重启,便于直接排查启动失败原因 - 添加资源限制适配Runner能力:
services: cosmosdb: # 移除restart: always配置 deploy: resources: limits: cpus: '2' memory: 4G reservations: cpus: '1' memory: 2G
3. 配置CI环境信任模拟器证书
将模拟器的自签名证书导入系统信任库,解决HTTPS连接验证问题:
- name: Trust Cosmos DB Emulator certificate run: | curl -k https://localhost:8081/_explorer/emulator.pem > emulatorcert.crt sudo cp emulatorcert.crt /usr/local/share/ca-certificates/ sudo update-ca-certificates
4. 优化GitHub Actions流程
- 延长任务超时时间:将
timeout-minutes从10调整为15,给模拟器足够的启动窗口 - 指定固定版本的模拟器镜像:避免
latest镜像的兼容性风险,例如使用mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:2.14.0
内容的提问来源于stack exchange,提问作者lordav
相关产品推荐
相关产品推荐

