我有一个在ASP中部署WEB API的容器。. NET Core试图连接到SQL Server数据库。我用的是Windows 10和Docker桌面。
我可以成功地连接到Docker容器与SQL Server管理工作室的SQL Server和我的ASP。. NET Core应用程序(没有容器)。
但是当我运行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)
...
docker-compose for SQL Server:
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"
docker-compose for WEB API:
web_api:
build:
dockerfile: WebApi/Dockerfile
ports:
- 5000:80
depends_on:
- sqlserver
Dockerfile for WEB API:
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"]
到SQL Server的连接字符串:
"ConnectionStrings": {
"SqlConnectionString": "Server=192.168.0.108,1433;Database=myDb;User Id=sa;Password=StrongPassword;"
}
默认情况下,容器连接到桥接驱动程序。从ASP访问sqlserver。. NET时,必须在连接字符串中使用sqlserver的容器名。这样的。
"ConnectionStrings": {
"SqlConnectionString": "Server=sqlserver,1433;Database=myDb;User Id=sa;Password=StrongPassword;"
}
有关更多网络细节,您可以运行下面的cmd命令。
docker network inspect bridge
检查桥梁的命令帮助很大:docker network inspect bridge
我有一个Windows开发机器来运行Visual studio和docker桌面。所以我试图从一个容器与asp.net core
应用程序连接到另一个与ms sql
运行
我使用host.docker.internal
作为数据源在我的连接字符串,它工作得很好
对不起,是我的错。
我只是忘了docker-compose up -d
命令不重建Docker映像。
我删除了所有的图像,并再次运行命令。
使用上面的配置,它对我来说工作得很好!