从 docker 容器连接到 SQL Server 数据库 [英] Connect to SQL Server database from a docker container
问题描述
我的机器上安装了适用于 Windows 的 docker.有一个面向 .net core 1.0.0 的控制台应用程序试图访问在不同 VM 上运行的 SQL Server 数据库.我可以从我的机器 ping 运行 SQL Server 的虚拟机.
I have docker for windows installed on my machine. There is a console application targeting .net core 1.0.0 that tries to access a SQL Server database running on a different VM. I can ping the VM running SQL Server from my machine.
当我尝试从我机器上的命令提示符使用 dotnet run
运行控制台应用程序时,它工作正常.但是当同一个应用程序在 docker 容器中运行时,我收到一条消息
When I try to run the console application using dotnet run
from the command prompt on my machine it works fine. But when the same application is run inside a docker container I get a message
发生与网络相关或特定于实例的错误建立与 SQL Server 的连接.未找到服务器或无法访问.验证实例名称是否正确并且SQL Server 配置为允许远程连接.(提供方:TCP提供程序,错误:40 - 无法打开与 SQL Server 的连接)
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 应用程序
- 在 MS SQL 中扩展数据库
- 右键单击安全/登录"
- 选择新登录"
- 创建用户名和密码.
- 分配服务器角色"...我使用了系统管理员,因为我只是在测试
- 在用户映射"下,我将我的新用户添加到我的数据库并使用dbo"作为架构.
右键单击您的数据库,选择属性/安全/服务器身份验证/SQL Server 和 Windows 身份验证模式"单选按钮.重新启动 MS SQL 服务.
Right click on your database, select 'Properties / Security / Server Authentication / SQL Server and Windows Authentication Mode' radio button. Restart the MS SQL service.
例子
"ConnectionStrings": {
"DefaultConnection": "Server=YourServerName;Database=YourDatabaseName;MultipleActiveResultSets=true;User Id=UserNameYouJustAdded;Password=PassordYouJustCreated"
},
确保删除Trusted_Connection=True
.
我的示例 Docker 文件
My example Docker file
FROM microsoft/dotnet:nanoserver
ARG source=.
WORKDIR /app
EXPOSE 5000
EXPOSE 1433
ENV ASPNETCORE_URLS http://+:5000
COPY $source .
发布应用
在提升的 PowerShell 中从与 Docker 文件相同的位置运行
Publish Application
Running from the same location as the Docker file in an elevated PowerShell
dotnet publish
docker build binDebug
etcoreapp1.0publish -t aspidserver
docker run -it aspidserver cmd
我想运行容器并查看它在 PowerShell 中运行时的输出.
I wanted to run the container and see the output as it was running in PowerShell.
一旦容器在命令提示符下启动并在容器中运行,我就启动了我的应用程序.
Once the container was up and running in the container at the command prompt I kicked off my application.
dotnet nameOfApplication.dll
如果一切按计划进行,则应该启动并运行.
If everything went to plan one should be up and running.
这篇关于从 docker 容器连接到 SQL Server 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!