docker server 容器连接sql,从Docker容器连接到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.

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

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)

I tried using

docker run --add-host sqldemo:

but that made no difference.

解决方案

Assumptions

Microsoft SQL Server 2016

Windows 10 Anniversary Update

Windows Containers

ASP.NET Core application

Add a SQL user to your SQL database.

In MS SQL expand the database

Right click on 'Security / Logins'

Select 'New Login'

Create a user name and password.

Assign a 'Server Role(s)'...I used sysadmin since I'm just testing

Under 'User Mapping' I added my new user to my database and used 'dbo' for schema.

Change SQL Authentication to allow SQL Server Authentication Mode

Right click on your database, select 'Properties / Security / Server Authentication / SQL Server and Windows Authentication Mode' radio button. Restart the MS SQL service.

Update your appsettings.json with your new user name and password

Example

"ConnectionStrings": {

"DefaultConnection": "Server=YourServerName;Database=YourDatabaseName;MultipleActiveResultSets=true;User Id=UserNameYouJustAdded;Password=PassordYouJustCreated"

},

Make sure you remove Trusted_Connection=True.

Create a Docker file

My example Docker file

FROM microsoft/dotnet:nanoserver

ARG source=.

WORKDIR /app

EXPOSE 5000

EXPOSE 1433

ENV ASPNETCORE_URLS http://+:5000

COPY $source .

Publish Application

Running from the same location as the Docker file in an elevated PowerShell

dotnet publish

docker build bin\Debug\netcoreapp1.0\publish -t aspidserver

docker run -it aspidserver cmd

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值