【发布时间】:2021-12-02 08:34:15
【问题描述】:
我是 docker 新手,正在尝试使用 docker-compose 将 .NET Core 3.0 应用程序与 SQL 数据库连接起来。
我在 docker-compose.yml 中定义了连接字符串。
我尝试过使用 127.0.0.1 和不提供端口(1433)。
这是我得到的例外:
webapi_1 | fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
webapi_1 | An error occurred using the connection to database 'InstaDb' on server '127.0.0.1,1433'.
webapi_1 | fail: Microsoft.EntityFrameworkCore.Query[10100]
webapi_1 | An exception occurred while iterating over the results of a query for context type 'Insta.Infra.Data.Context.InstaDbContext'.
webapi_1 | 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)
docker-compose.yml
version: "3.9"
services:
webapi:
build: .
ports:
- "5000:80"
depends_on:
- db
environment:
ConnectionStrings:InstaDBConnection: "Server=127.0.0.1,1433;Database=InstaDb;User=sa;Password=#Admin123;MultipleActiveResultSets=True;"
db:
image: "mcr.microsoft.com/mssql/server"
environment:
SA_PASSWORD: "#Admin123"
ACCEPT_EULA: "Y"
Dockerfile
FROM mcr.microsoft.com/dotnet/sdk:3.1 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
WORKDIR /src
COPY ["Insta.Mvc/Insta.Mvc.csproj", "Insta.Mvc/"]
COPY ["Insta.Infra.Data/Insta.Infra.Data.csproj", "Insta.Infra.Data/"]
COPY ["Insta.Application/Insta.Application.csproj", "Insta.Application/"]
COPY ["Insta.Domain/Insta.Domain.csproj", "Insta.Domain/"]
COPY ["Insta.Common.Utils/Insta.Common.Utils.csproj", "Insta.Common.Utils/"]
COPY ["Insta.Infra.IoC/Insta.Infra.IoC.csproj", "Insta.Infra.IoC/"]
RUN dotnet restore "Insta.Mvc/Insta.Mvc.csproj"
COPY . .
WORKDIR "/src/Insta.Mvc"
RUN dotnet build "Insta.Mvc.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "Insta.Mvc.csproj" -c Release -o /app/publish
WORKDIR /src
RUN chmod +x ./entrypoint.sh
CMD /bin/bash ./entrypoint.sh
WORKDIR "/src/Insta.Mvc"
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Insta.Mvc.dll"]
【问题讨论】:
-
您是否也在 webapi 容器中安装了 SQL Server? Docker 容器本质上是它们自己的小型 Linux VM,
localhost和127.0.0.1指向它们自己。如果您已发布 db 容器的端口 1433,您是否尝试过在连接字符串中使用Server=host.docker.internal,1433;? (注意:这只适用于 Docker Desktop,不适用于 Docker 生产环境。)
标签: .net sql-server docker-compose