How to connect external MS SQL server database from container - sql-server

I'm new in Docker and we are migrating our working ASP.NET CORE app to Docker in company
Problem is I did't find any releated topics about how to connect to external already existing MS SQL server [not in docker image] database from container.
All topics are about connecting to official Image of MS SQL-Server[which I don't need].
I wrote Dockerfile and application running but there no connection to SQL Server
Please give me correct direction with topics or hints thank you!
Dockerfile
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS base
WORKDIR /app
EXPOSE 5000 //port to app
EXPOSE 1433 //SQL-Server port
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY UploadCore/UploadCore.csproj UploadCore/
RUN dotnet restore UploadCore/UploadCore.csproj
COPY . .
WORKDIR /src/UploadCore
RUN dotnet build UploadCore.csproj -c Release -o /app
FROM build AS publish
RUN dotnet publish UploadCore.csproj -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "UploadCore.dll"]
I'm running my app as below
docker run -it --rm -p 5000:5000 -p 1433:1433 --name UploadCore my-app_test:4.5
Error:
Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'MIS_REPORTS' on server 'server02'.
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
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: SQL Network Interfaces, error: 25 - Connection string is not valid: Connection string is not valid)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, SqlAuthenticationMethod authType)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, DbConnectionPool pool)

Docker provides its own internal DNS service that can do things like resolve other container names as host names. It looks like you've configured your database location as a bare host name server02. This hits the Docker DNS resolver first, and it tries to resolve it as a container name; when that fails, that's why you're getting the error you do.
In different environments you can tell this apart from different kinds of errors by error messages like "name resolution failed" or "no such host"; this is different from an error message like "connection refused" or "connection reset by peer".
You can resolve this by using a fully-qualified domain name (FQDN) as your database location; for example, server02.example.com instead of just server02. Since that doesn't look like a container name, it will cause Docker to forward the DNS request to your normal name server.

Related

Unable to connect from data studio to SQL Server 2022 running on Docker

I am trying to connect to SQL Server running on docker. I am on windows 11 with WSL ubuntu 22.04.1.
This is how I start my instance by running this command in powershell.
docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=password123" -p 1433:1433 -d mcr.microsoft.com/mssql/server:2022-latest
In Azure Data Studio (also tried SSMS), I connect using these settings (leaving the rest at defaults):
Connection type: Microsoft SQL server
server: localhost // also tried localhost,1433 and 0.0.0.0,1433
user name: sa
password: password123
which gives me the following error
(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
---> System.ComponentModel.Win32Exception (2): The system cannot find the file specified.
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnectionString connectionOptions, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.<>c__DisplayClass48_0.<CreateReplaceConnectionContinuation>b__0(Task`1 _)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.ReliableSqlConnection.<>c__DisplayClass30_0.<<OpenAsync>b__0>d.MoveNext() in D:\a\_work\1\s\src\Microsoft.SqlTools.ManagedBatchParser\ReliableConnection\ReliableSqlConnection.cs:line 312
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ConnectionService.TryOpenConnection(ConnectionInfo connectionInfo, ConnectParams connectionParams) in D:\a\_work\1\s\src\Microsoft.SqlTools.ServiceLayer\Connection\ConnectionService.cs:line 666
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:2,State:0,Class:20
and when I try server: localhost,1433 the error changes into:
provider: TCP Provider, error: 0 - An attempt was made to access a socket in a way forbidden by its access permissions.)
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: 0 - An attempt was made to access a socket in a way forbidden by its access permissions.)
---> System.ComponentModel.Win32Exception (10013): An attempt was made to access a socket in a way forbidden by its access permissions.
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnectionString connectionOptions, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.<>c__DisplayClass48_0.<CreateReplaceConnectionContinuation>b__0(Task`1 _)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.ReliableSqlConnection.<>c__DisplayClass30_0.<<OpenAsync>b__0>d.MoveNext() in D:\a\_work\1\s\src\Microsoft.SqlTools.ManagedBatchParser\ReliableConnection\ReliableSqlConnection.cs:line 312
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ConnectionService.TryOpenConnection(ConnectionInfo connectionInfo, ConnectParams connectionParams) in D:\a\_work\1\s\src\Microsoft.SqlTools.ServiceLayer\Connection\ConnectionService.cs:line 666
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:10013,State:0,Class:20
edit: I tried the following to no avail
net stop hns
net start hns
running azure data studio as administrator.
updating azure data studio to latest version.
edit2: solved, ping localhost resolves to ::1 which is default ipv6 protocol as default instead of ipv4, thanks #AlwaysLearning

Can't connect to SQL SERVER running on docker

I've installed a sqlserver docker container and it seems that the instalation its fine, as shown bellow:
I've setup the server using this command:
docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=<#MystrongPassword1" -p 1433:1433 --name sql1 --hostname sql1 -d mcr.microsoft.com/mssql/server:2022-latest
The problem is: I'm trying to create a connection on Azure Data Studio, this is the configuration I'm using
When I click the "Connect" button, it doesnt connect and the below errors are shown:
When the first error apears, I click the "enable trust certificate" button, and then the second error pop up appears and the connection fails:
The error details:
Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user 'sa'.
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.<>c__DisplayClass48_0.<CreateReplaceConnectionContinuation>b__0(Task`1 _)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.ReliableSqlConnection.<>c__DisplayClass30_0.<<OpenAsync>b__0>d.MoveNext() in D:\a\_work\1\s\src\Microsoft.SqlTools.ManagedBatchParser\ReliableConnection\ReliableSqlConnection.cs:line 312
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ConnectionService.TryOpenConnection(ConnectionInfo connectionInfo, ConnectParams connectionParams) in D:\a\_work\1\s\src\Microsoft.SqlTools.ServiceLayer\Connection\ConnectionService.cs:line 666
ClientConnectionId:cbab63a5-c831-442e-b117-eb024e6f16bf
Error Number:18456,State:1,Class:14
I just deleted it all and created all the same but this time it worked

ManagedIdentityCredential authentication unavailable. No Managed Identity endpoint found

we have a nightly process (all running on Azure VMs) which is largely a collection of powershell scripts to update DBs in our TEST environment. Quite frequently we hit issues like below. We have around 25 DBs to update and at some random point in the process we'll have sporadic errors trying to use Azure Managed Identity Authentication. Below shows how it all works perfectly for one DB, but then fails on the next DB even though run from the same process on the same Azure VM and connecting to the same SQL Managed Instance where the source VM's Managed Identity is configured to have full sysAdmin rights.
I've previously been advised in effect, "these services just aren't that reliable so you just need to wrap all such logic in retry logic and hope you eventually get lucky". The frequency with which we see these issues is making me wonder if there is more going on than that and if anyone has seen this or has other ideas? If the nature of these services are such that it just isn't that reliable to work every time, you'd think they would add the retry logic in the core libraries such as Microsft.Data.SqlClient or the underlying Azure.Identity libraries vs expecting developers to detect these issues higher in the logic chain and respond?
Anyway, I'm not sure if anyone else has seen this or I'm just unlucky :)
[06:51:56][Step 5/6] ========================================================================
[06:51:56][Step 5/6] Updating DB zzzzz_Regression (zzzzzRegression) on server xxxxx-tcc-sql.2222.database.windows.net (xxxxx-TCC-SQL)
[06:51:56][Step 5/6] ========================================================================
[06:51:57][Step 5/6] 6:51:56 AM:Using env file from command line: .\Package\BuildScripts\Configs\mmmmmTestAzure.fmenv.xml
[06:51:57][Step 5/6] 6:51:57 AM:Loaded environment: mmmmmTestAzure
[06:51:57][Step 5/6] 6:51:57 AM:Applying change scripts.
[06:52:09][Step 5/6] 6:52:09 AM:Creating functions.
[06:52:27][Step 5/6] 6:52:27 AM:Creating triggers.
[06:52:34][Step 5/6] 6:52:34 AM:Creating stored procedures.
[06:54:08][Step 5/6] 6:54:07 AM:Database FM3OMS_Regression upgraded successfully.
[06:54:08][Step 5/6] Inializing Report Urls on Database Id zzzzzRegression
[06:54:14][Step 5/6] ========================================================================
[06:54:14][Step 5/6] Updating DB yyyyy (yyyyy) on server xxxxx-tcc-sql.2222.database.windows.net (xxxxx-TCC-SQL)
[06:54:14][Step 5/6] ========================================================================
[06:54:14][Step 5/6] 6:54:14 AM:Using env file from command line: .\Package\BuildScripts\Configs\mmmmmTestAzure.fmenv.xml
[06:54:15][Step 5/6] 6:54:14 AM:Loaded environment: mmmmm
[06:54:15][Step 5/6] 6:54:14 AM:Applying change scripts.
[06:54:28][Step 5/6] 6:54:28 AM:Creating functions.
[06:54:52][Step 5/6] 6:54:52 AM:Creating triggers.
[06:55:10][Step 5/6] 6:55:03 AM:Creating stored procedures.
[06:57:39][Step 5/6] 6:57:39 AM:Database yyyyy upgraded successfully.
[06:57:42][Step 5/6] Inializing Report Urls on Database Id yyyyy
[06:58:18][Step 5/6] Initialize-FMReportUrls : 6:58:07 AM:Using env file from command line:
[06:58:18][Step 5/6] .\Package\BuildScripts\Configs\mmmmmTestAzure.fmenv.xml 6:58:13 AM:Loaded environment: mmmmmTestAzure
[06:58:18][Step 5/6] System.AggregateException: One or more errors occurred. ---> Azure.Identity.CredentialUnavailableException:
[06:58:18][Step 5/6] ManagedIdentityCredential authentication unavailable. No Managed Identity endpoint found. at
[06:58:18][Step 5/6] Azure.Identity.ManagedIdentityClient.<AuthenticateAsync>d__12.MoveNext() --- End of stack trace from previous location
[06:58:18][Step 5/6] where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at
[06:58:18][Step 5/6] System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at
[06:58:18][Step 5/6] Azure.Identity.ManagedIdentityCredential.<GetTokenImplAsync>d__9.MoveNext() --- End of stack trace from previous
[06:58:18][Step 5/6] location where exception was thrown --- at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex)
[06:58:18][Step 5/6] at Azure.Identity.ManagedIdentityCredential.<GetTokenImplAsync>d__9.MoveNext() --- End of stack trace from previous
[06:58:18][Step 5/6] location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
[06:58:18][Step 5/6] task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at
[06:58:18][Step 5/6] Azure.Identity.ManagedIdentityCredential.<GetTokenAsync>d__7.MoveNext() --- End of stack trace from previous location
[06:58:18][Step 5/6] where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at
[06:58:18][Step 5/6] System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at
[06:58:18][Step 5/6] System.Threading.Tasks.ValueTask`1.get_Result() at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.<AcquireTokenAsync>d__19.MoveNext() --- End of inner
[06:58:18][Step 5/6] exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
[06:58:18][Step 5/6] at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) at
[06:58:18][Step 5/6] System.Threading.Tasks.Task`1.get_Result() at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.SqlInternalConnectionTds.GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.SqlInternalConnectionTds.OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
[06:58:18][Step 5/6] BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
[06:58:18][Step 5/6] BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword,
[06:58:18][Step 5/6] SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover, Boolean
[06:58:18][Step 5/6] isFirstTransparentAttempt, Boolean disableTnir) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword,
[06:58:18][Step 5/6] SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential
[06:58:18][Step 5/6] credential, TimeoutTimer timeout) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer
[06:58:18][Step 5/6] timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString
[06:58:18][Step 5/6] newSecurePassword, Boolean redirectedUserInstance) at
This is a problem with the Azure VM, or an issue with Microsoft.Data.SqlClient.
ManagedIdentityCredential authentication unavailable. No Managed
Identity endpoint found.
This message claims that the local http endpoint that Azure provides when you enable Managed Identity on a VM is not available to hand out access tokens.
You should
make sure you're current on Microsoft.Data.SqlClient,
open an Azure Support incident and/or create an issue in the SqlClient repo, or perhaps the Azure.Identity repo and
switch to SQL Auth, or non-MSI AAD auth (eg ActiveDirectoryServicePrincipal where you use the ClientId as the user name and a Client Secret as the password or ActiveDirectoryDefault which supports supplying the ClientID and ClientSecret in environment variables) as a workaround.

Application running on Linux Docker image, is unable to connect to SQL server on local windows machine

I have trying to dockerize my a ASP.Net Core 2.2 web application by running on Linux Docker image. I am however getting the following error when it is trying to connect to SQL server running on local windows machine.
Some of the things that I have tried are:
enabling TCP\IP in SQL Server Network configuration, the Listen All is set to yes, IPAddress=> IPAll=>TCP Port=49172
turning off windows firewall on public network.
Changing my SQL server connection string to use my IPv4 address eg: instead of DataSource=DESKTOP-2LS7578\\SQLEXPRESS use DataSource=192.168.18.65\\SQLEXPRESS
Added rule in Windows firewall to allow inbound traffic from port 49172, changed my SQL server connection string to use the IP Address listed under DockerNAT and port 49172. eg: instead of DataSource=DESKTOP-2LS7578\\SQLEXPRESS use DataSource=<IP Address listed under NAT>\\SQLEXPRESS:49172
ensured that my sql server browser service is running.
Update 2(using Instructions from here):
changed my SQL server connection string to use the port listed under SQL Server Network configuration=> TCP\IP => IPAddress=> IPAll=>TCP Dynamic Port so it becomes "host.docker.internal\SQLEXPRESS,"
Enable firewall for the port you've found
What else can I try?
StackTrace:
An unhandled exception occurred while processing the request.
SocketException: Success
Microsoft.Data.SqlClient.SNI.SSRP.GetPortByInstanceName(string browserHostName, string instanceName)
SqlException: 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: 25 - Connection string is not valid)
Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, object providerInfo, string newPassword, SecureString newSecurePassword, bool redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, bool applyTransientFaultHandling, string accessToken)
Dockerfile:
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
WORKDIR /src
COPY ["Scrubber/Scrubber.csproj", "Scrubber/"]
COPY ["SimplerProducts.MicrosoftEntityFrameworkCoreStorage/SimplerProducts.MicrosoftEntityFrameworkCoreStorage.csproj", "SimplerProducts.MicrosoftEntityFrameworkCoreStorage/"]
RUN dotnet restore "Scrubber/Scrubber.csproj"
COPY . .
WORKDIR "/src/Scrubber"
RUN dotnet build "Scrubber.csproj" -c Release -o /app
FROM build AS publish
RUN dotnet publish "Scrubber.csproj" -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "Scrubber.dll"]
I was able to get the application working by not specifiying the instance name in the connection string and using SQL server authentication.
i.e change the connection string from Data Source=DESKTOP-2LS7578\\SQLEXPRESS;Integrated Security=True; to Data Source=host.docker.internal,1433;User ID=<UserID>;Password=<Password>;

SQL Server not working after upgrading windows8.1 to windows 10

TITLE: Connect to Server
------------------------------
Cannot connect to Thejus-PC.
------------------------------ ADDITIONAL INFORMATION:
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: Named
> Pipes Provider, error: 40 - Could not open a connection to SQL Server)
> (.Net SqlClient Data Provider)
>
> ------------------------------ For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=2&LinkId=20476
>
> ------------------------------ Error Number: 2 Severity: 20 State: 0
>
>
> ------------------------------ Program Location:
>
> at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
> exception, Boolean breakConnection, Action`1 wrapCloseInAction) at
> System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
> stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
> System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo,
> SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout,
> Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean
> integratedSecurity, Boolean withFailover, SqlAuthenticationMethod
> authType) at
> System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
> serverInfo, String newPassword, SecureString newSecurePassword,
> Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean
> withFailover) at
> System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
> serverInfo, String newPassword, SecureString newSecurePassword,
> Boolean redirectedUserInstance, SqlConnectionString connectionOptions,
> SqlCredential credential, TimeoutTimer timeout) at
> System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer
> timeout, SqlConnectionString connectionOptions, SqlCredential
> credential, String newPassword, SecureString newSecurePassword,
> Boolean redirectedUserInstance) at
> System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
> identity, SqlConnectionString connectionOptions, SqlCredential
> credential, Object providerInfo, String newPassword, SecureString
> newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString
> userConnectionOptions, SessionData reconnectSessionData,
> DbConnectionPool pool, String accessToken) at
> System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
> options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo,
> DbConnectionPool pool, DbConnection owningConnection,
> DbConnectionOptions userOptions) at
> System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection
> owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions
> userOptions) at
> System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
> owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions
> userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&
> connection) at
> System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
> outerConnection, DbConnectionFactory connectionFactory,
> TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at
> System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
> outerConnection, DbConnectionFactory connectionFactory,
> TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at
> System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1
> retry) at
> System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1
> retry) at System.Data.SqlClient.SqlConnection.Open() at
> Microsoft.SqlServer.Management.SqlStudio.Explorer.ObjectExplorerService.ValidateConnection(UIConnectionInfo
> ci, IServerType server) at
> Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()
>
> ===================================
>
> The system cannot find the file specified
Please verify that Service "SQL Server (MSSQLSERVER)" is started.
I started the "SQL Server (MSSQLSERVER)" service and now i am able get into Sql server.
Please verify that Service "SQL Server (MSSQLSERVER)" is started. Just now I upgraded to Windows 10 and got the same issue.
I started the "SQL Server (MSSQLSERVER)" service and now I am able get into Sql server.
We have encountered this problem with Windows 7 and Windows 8. After the upgrade SQL Server does not start. We have been able to start it manually, but it will not start automatically.
So far our only solution has been to uninstall and reinstall SQL Server.
Try changing your connection string to IP/NameInstance, it works for me. Before I used to have localhost/NameInstance in my connection string but since I updated to windows 10, it did not work anymore.

Resources