Can't connect to SQL SERVER running on docker - sql-server

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

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

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.

How to connect external MS SQL server database from container

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.

Dotnet and sql docker image show error and not show api data

I build a web api in dotnet core using entityframe work. It is runing sucessfully and show data when I run by using IIS. I can also use the swager and postman for CRUD Operations. I also create a sql docker image which is up and runing with sql1 name. However when I try to build docker images of my webapi I see the following error. I didnt manage to find out the core issu. Please help.
{"EventId":0,"LogLevel":"Error","Category":"AngularAppApi.Program","Message":"An error occurred while migrating the database.","Exception":"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: Could not open a connection to SQL Server) at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action\u00601 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, 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.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal\u0026 connection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource\u00601 retry, DbConnectionOptions userOptions, DbConnectionInternal\u0026 connection) at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource\u00601 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal\u0026 connection) at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource\u00601 retry, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource\u00601 retry, DbConnectionOptions userOptions) at
Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource\u00601 retry, SqlConnectionOverrides overrides) at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.\u003C\u003Ec__DisplayClass18_0.\u003CExists\u003Eb__0(DateTime giveUp) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.\u003C\u003Ec__DisplayClass12_0\u00602.\u003CExecute\u003Eb__0(DbContext c, TState s) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func\u00603 operation, Func\u00603 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func\u00602 operation, Func\u00602 verifySucceeded) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists) at
Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists() at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists() at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade) at AngularAppApi.MigrateDatabase.Migrate[T](IHost webHost) in /app/MigrateDatabase.cs:line 22 ClientConnectionId:00000000-0000-0000-0000-000000000000","State":{"Message":"An error occurred while migrating the database.","{OriginalFormat}":"An error occurred while migrating the database."}}
{"EventId":0,"LogLevel":"Error","Category":"AngularAppApi.Program","Message":"An error occurred while migrating the database.","Exception":"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: Could not open a connection to SQL Server) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal\u0026 connection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource\u00601 retry, DbConnectionOptions userOptions, DbConnectionInternal\u0026 connection) at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource\u00601 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal\u0026 connection) at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource\u00601 retry, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource\u00601 retry, DbConnectionOptions userOptions) at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource\u00601 retry, SqlConnectionOverrides overrides) at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.\u003C\u003Ec__DisplayClass18_0.\u003CExists\u003Eb__0(DateTime giveUp) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.\u003C\u003Ec__DisplayClass12_0\u00602.\u003CExecute\u003Eb__0(DbContext c, TState s) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func\u00603 operation, Func\u00603 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func\u00602 operation, Func\u00602 verifySucceeded) at
Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists() at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureDeleted() at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureDeleted() at AngularAppApi.Program.Main(String[] args) in /app/Program.cs:line 23 ClientConnectionId:00000000-0000-0000-0000-000000000000","State":{"Message":"An error occurred while migrating the database.","{OriginalFormat}":"An error occurred while migrating the database."}}
{"EventId":14,"LogLevel":"Information","Category":"Microsoft.Hosting.Lifetime","Message":"Now listening on: http://[::]:80","State":{"Message":"Now listening on: http://[::]:80","address":"http://[::]:80","{OriginalFormat}":"Now listening on: {address}"}}
{"EventId":0,"LogLevel":"Information","Category":"Microsoft.Hosting.Lifetime","Message":"Application started. Press Ctrl\u002BC to shut down.","State":{"Message":"Application started. Press Ctrl\u002BC to shut down.","{OriginalFormat}":"Application started. Press
Ctrl\u002BC to shut down."}}
{"EventId":0,"LogLevel":"Information","Category":"Microsoft.Hosting.Lifetime","Message":"Hosting environment: Production","State":{"Message":"Hosting environment: Production","envName":"Production","{OriginalFormat}":"Hosting environment: {envName}"}}
{"EventId":0,"LogLevel":"Information","Category":"Microsoft.Hosting.Lifetime","Message":"Content root path: /app","State":{"Message":"Content root path: /app","contentRoot":"/app","{OriginalFormat}":"Content root path: {contentRoot}"}}
As you can see its not able to find the server or database but my sql server image is up a runing.
I am using fowolling commad to build the images.
docker run --name dockerwebapi4angular --link sql1:sql1 -e "ServerName=sql1" -e "Database=Projects" -e "UserName=sa" -e "Password=41414141" -p 8181:80 dockersql
Can you please help me to find what I did wrong?
my Docker file is this,
FROM mcr.microsoft.com/dotnet/sdk:6.0 as build
WORKDIR /app
COPY *csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o pub
#Run phase
FROM mcr.microsoft.com/dotnet/aspnet:6.0
WORKDIR /app
EXPOSE 80
COPY --from=build /app/pub .
ENTRYPOINT [ "dotnet","AngularAppApi.dll" ]

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