Vol*_*huk 2 c# sql-server asp.net docker asp.net-core
我有一个在 ASP.NET Core 中部署 WEB API 的容器,试图连接到 SQL Server 数据库。我正在使用 Docker Desktop 运行 Windows 10。
我可以从 SQL Server Management Studio 和我的 ASP.NET Core 应用程序(无容器)成功连接到具有 SQL Server 的 Docker 容器。
但是当我在容器内运行 ASP.NET Core 时,出现错误:
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HMCRFGHIEO1Q", Request id "0HMCRFGHIEO1Q:00000002": An unhandled exception was thrown by the application.
Microsoft.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
...
Run Code Online (Sandbox Code Playgroud)
SQL Server 的 docker-compose:
sqlserver:
image: mcr.microsoft.com/mssql/server:2019-latest
ports:
- 1433:1433
volumes:
- my-volume:/var/opt/mssql
environment:
SA_PASSWORD: "StrongPassword"
ACCEPT_EULA: "Y"
Run Code Online (Sandbox Code Playgroud)
用于 WEB API 的 docker-compose:
web_api:
build:
dockerfile: WebApi/Dockerfile
ports:
- 5000:80
depends_on:
- sqlserver
Run Code Online (Sandbox Code Playgroud)
WEB API 的 Dockerfile:
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["WebApi/WebApi.csproj", "WebApi/"]
RUN dotnet restore "WebApi/WebApi.csproj"
COPY . .
WORKDIR "/src/WebApi"
RUN dotnet build "WebApi.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "WebApi.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApi.dll"]
Run Code Online (Sandbox Code Playgroud)
SQL Server 的连接字符串:
"ConnectionStrings": {
"SqlConnectionString": "Server=192.168.0.108,1433;Database=myDb;User Id=sa;Password=StrongPassword;"
}
Run Code Online (Sandbox Code Playgroud)
小智 7
默认情况下,容器连接到桥驱动程序。要从 ASP.NET 访问 sqlserver,必须在连接字符串中使用 sqlserver 的容器名称。像这样。
"ConnectionStrings": {
"SqlConnectionString": "Server=sqlserver,1433;Database=myDb;User Id=sa;Password=StrongPassword;"
}
Run Code Online (Sandbox Code Playgroud)
有关更多网络详细信息,您可以运行下面的 cmd 命令。
docker network inspect bridge
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5341 次 |
| 最近记录: |