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

在Docker中运行含Testcontainers的.NET集成测试遇连接问题

问题解决方案

1. 修正Dockerfile测试阶段配置

移除硬编码的DOCKER_HOST,改为通过环境变量和挂载套接字让Testcontainers自动识别Docker daemon:

FROM build AS tests
WORKDIR /src
# 设置环境变量指定Docker套接字路径
ENV DOCKER_HOST=unix:///var/run/docker.sock
# 构建时显式挂载宿主机Docker套接字到容器内
RUN --mount=type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock \
    dotnet test --no-build -c Release --results-directory /testresults --logger "trx;LogFileName=testresults_authentication_api_it.trx" /p:CollectCoverage=true /p:CoverletOutputFormat=json%2cCobertura /p:CoverletOutput=/testresults/coverage/ -p:MergeWith=/testresults/coverage/coverage.json  Authentication.Api/MyProject.Authentication.Api.IntegrationTests/MyProject.Authentication.Api.IntegrationTests.csproj

2. 调整构建命令(Windows环境)

由于Windows使用Linux容器时,宿主机Docker套接字路径为//./pipe/docker_engine,构建命令需修改为:

docker build --progress=plain -f Authentication.Api\MyProject.Authentication.Api\Dockerfile --target tests --tag myproject-tests --mount=type=bind,source=//./pipe/docker_engine,target=/var/run/docker.sock .

3. 移除Testcontainers硬编码端点

在MsSqlDatabaseProvider.cs中删除.WithDockerEndpoint("tcp://192.168.99.100:2376"),恢复自动检测逻辑:

public MsSqlDatabaseProvider() =>
    Database = new TestcontainersBuilder<MsSqlTestcontainer>()
        .WithDatabase(new MsSqlTestcontainerConfiguration
        {
            Password = DbPassword,
        })
        .WithImage(DbImage)
        .WithCleanUp(true)
        .Build();

4. Azure DevOps流水线适配要点

  • 选择支持Docker的托管代理镜像(如ubuntu-latest或配置Linux容器的windows-latest)
  • 确保流水线中Docker服务已启用,构建命令同样需挂载Docker套接字
  • 若使用自托管代理,需提前配置代理节点的Docker访问权限

错误原因说明

  • 192.168.99.100:2376是旧版Docker Toolbox的默认地址,当前Docker Desktop(Windows+Linux容器)使用host.docker.internal作为宿主机别名,或通过套接字文件访问Docker daemon
  • Dockerfile中的VOLUME仅为卷声明,构建阶段不会自动挂载,必须通过docker build的--mount参数显式绑定宿主机套接字
  • Testcontainers需要调用宿主机Docker daemon创建子容器,因此容器内必须能正确连接到宿主机的Docker服务

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:20:28