我的机器上安装了 docker for windows。有一个针对 .net core 1.0.0 的控制台应用程序,它尝试访问在不同 VM 上运行的 SQL Server 数据库。我可以从我的机器 ping 运行 SQL Server 的 VM。
当我尝试使用 dotnet run
从我的机器上的命令提示符运行控制台应用程序时,它工作正常。但是当同一个应用程序在 docker 容器中运行时,我会收到一条消息
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 run --add-host sqldemo:<VM running sql server ip here>
但这没什么区别。
最佳答案
假设
- Microsoft SQL Server 2016
- Windows 10 周年更新
- Windows 容器
- ASP.NET Core 应用程序
将 SQL 用户添加到您的 SQL 数据库。
- 在 MS SQL 中展开数据库
- 右键点击“安全/登录”
- 选择“新登录”
- 创建用户名和密码。
- 分配一个“服务器角色”...我使用的是系统管理员,因为我只是在测试
- 在“用户映射”下,我将新用户添加到我的数据库并使用“dbo”作为架构。
更改 SQL 身份验证以允许 SQL Server 身份验证模式
右键单击您的数据库,选择“属性/安全/服务器身份验证/SQL Server 和 Windows 身份验证模式”单选按钮。重启 MS SQL 服务。
用您的新用户名和密码更新您的 appsettings.json
例子
"ConnectionStrings": {
"DefaultConnection": "Server=YourServerName;Database=YourDatabaseName;MultipleActiveResultSets=true;User Id=UserNameYouJustAdded;Password=PassordYouJustCreated"
},
确保删除 Trusted_Connection=True
。
创建一个 Docker 文件
我的示例 Docker 文件
FROM microsoft/dotnet:nanoserver
ARG source=.
WORKDIR /app
EXPOSE 5000
EXPOSE 1433
ENV ASPNETCORE_URLS http://+:5000
COPY $source .
发布应用程序
在提升的 PowerShell 中从与 Docker 文件相同的位置运行
dotnet publish
docker build bin\Debug\netcoreapp1.0\publish -t aspidserver
docker run -it aspidserver cmd
我想运行容器并查看它在 PowerShell 中运行时的输出。
一旦容器在命令提示符下启动并在容器中运行,我就启动了我的应用程序。
dotnet nameOfApplication.dll
如果一切按计划进行,应该可以启动并运行。
关于c# - 从 docker 容器连接到 SQL Server 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38578751/