docker中的ConnectionString无法连接

问题描述 投票:0回答:1

我有一个

docker-compose.yml
文件来运行 SQL Server 和由 ABP.io 搭建的 C# ASP.NET Core Web API:

services:
    my-api:
        container_name: my-api
        environment:
            - ASPNETCORE_ENVIRONMENT=Docker
        depends_on:
            - sqlserver
        ports:
            - "44353:44353"
    sqlserver:
        container_name: sqlserver
        image: mcr.microsoft.com/mssql/server:2022-latest
        environment:
            - MSSQL_SA_PASSWORD=p@ssw0rd
            - ACCEPT_EULA=Y
        ports:
            - "1433:1433"
      

这是我的

MyApi
的 Dockerfile:

FROM mcr.microsoft.com/dotnet/aspnet:8.0  AS base
COPY bin/Release/net8.0/publish/ app/
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src

FROM base AS final
WORKDIR /app
COPY --from=build /src .

ENTRYPOINT ["dotnet", "MyApi.dll"]

我的问题是 API 由于连接字符串而无法启动:

Server=sqlserver,1433;Database=MyDatabase;User ID=sa;pwd=p@ssw0rd;TrustServerCertificate=True

但我不明白为什么,因为:

  • 当我尝试使用 sqlcmd 或 SQL Server Management Studio 从主机连接到 docker 数据库时,它工作正常
  • 如果我在堆栈内创建一个 ubuntu docker 通过 docker 名称 ping 我的机器 (
    sqlserver
    ),它也可以工作
  • 如果我使用此命令行在 ubuntu docker 中运行
    sqlcmd
    /opt/mssql-tools18/bin/sqlcmd -S sqlserver,1433 -U sa -P p@ssw0rd -C
    它可以工作
  • 如果我使用 docker 外部的 docker 连接字符串(直接从 Visual Studio)运行
    MyApi
    ,它可以工作

我真的不明白我的案例有什么遗漏或错误。

我还克隆了这个仓库docker-compose-demo来检查它是否有效,事实确实如此。

这是 ABP.io 特有的东西吗?我暂时一无所知

编辑:另外,我不确定它是否相关,但在docker日志中,我看到了这个:

2024-11-29 14:24:02 [19:24:02 ERR] An error occurred using the connection to database 'MyDatabase' on server 'sqlserver,1433'.
...
2024-11-29 14:24:02 [19:24:02 ERR] Object reference not set to an instance of an object.
2024-11-29 14:24:02 System.NullReferenceException: Object reference not set to an instance of an object.
2024-11-29 14:24:02    at Microsoft.Data.Common.ADP.LocalMachineRegistryValue(String subkey, String queryvalue)
2024-11-29 14:24:02    at Microsoft.Data.SqlClient.TdsParserStaticMethods.AliasRegistryLookup(String& host, String& protocol)
2024-11-29 14:24:02    at Microsoft.Data.SqlClient.SqlInternalConnectionTds.ResolveExtendedServerName(ServerInfo serverInfo, Boolean aliasLookup, SqlConnectionString options)
c# docker docker-compose entity-framework-core
1个回答
0
投票

我今天遇到了这个问题。我发现我的问题在csproj中如下

<RuntimeIdentifier>win-x64</RuntimeIdentifier>
© www.soinside.com 2019 - 2024. All rights reserved.