Cannot access SQL Server from microservice code inside Docker container

Continuing the discussion from Auth container not starting in Windows 2019:

Hi Akos,

Thanks for your reply. I have pasted below the block of code in the microservice that the Docker container runs, the error occurs inside the try statement, where it makes a call to SQL server:

        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        /// </summary>
        /// <param name="services">Services object to register dependencies</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            Logger.LogDebug("Initializing Identity Server...");
            var builder = services.AddIdentityServer();

            // Get  APM scope list
            Mdrx.PM.Server.Security.Data.Token objToken = (Mdrx.PM.Server.Security.Data.Token)new TokenFactoryImpl().Create(null);
            var objConstringProvider = new ConnectionStringProvider();
            objToken.SecurityDsn = System.Environment.GetEnvironmentVariable("APMSecurityDSN");
            Logger.LogDebug($"SecurityDb connecting to '{objToken.SecurityDsn}'...");

            builder.Services.AddMvc(op =>
            {
                op.EnableEndpointRouting = false;
            });

            IdentityModelEventSource.ShowPII = true;

            Register.Services(services);

            Mdrx.PM.Server.SharedSource.Container.Register((i, c) => services.AddScoped(i, c));
            Mdrx.PM.Server.Security.Common.Container.Register((i, f) => services.AddScoped(i, f));
            Mdrx.PM.Server.SharedSource.Error.Container.Register((i, f) => services.AddScoped(i, f));

            // ==================================================
            // Security 
            // ==================================================
            Mdrx.PM.Server.Security.IO.Lib.Container.Register((i, c) => services.AddScoped(i, c));
            Mdrx.PM.Server.Security.Svr.Lib.Container.Register((i, c) => services.AddScoped(i, c));

            // ==================================================
            //  Error
            // ==================================================
            Mdrx.PM.Server.Error.SvrUtils.Container.Register((i, c) => services.AddScoped(i, c));


            builder.Services.AddHealthChecks();
            builder.Services.AddHttpContextAccessor();

            builder.Services
                .AddScoped<Mdrx.PM.Common.TimeZoneUtils.TZAUtils, Mdrx.PM.Common.TimeZoneUtils.TZAUtils>()
                .AddScoped<Mdrx.PM.Server.Common.IOUtils.IOUtils, Mdrx.PM.Server.Common.IOUtils.IOUtils>()
                .AddScoped<Mdrx.PM.Server.Security.IClientLicenseManager, ClientLicenseManager>()
                //.AddScoped<IErrorConsumer, > ()
                .AddServiceDiscovery()
                //.AddRestClient()
                .AddCorrelation()
                .AddGlobalErrorServices();
            

            // get the scopes
            var objScopeReaderLogger = loggerFactory.CreateLogger<AllscriptsPM.ScopeReader>();

            builder.Services.AddTransient<Mdrx.PM.Server.ITokenFactory, TokenFactoryImpl>();
            builder.Services.AddTransient<ISqlDataAccess, Mdrx.PM.Server.SharedSource.SqlDataAccess>();


            // add token as singleton so that it will be passed to the constructors of other services
            builder.Services.AddSingleton<Mdrx.PM.Server.Security.Data.Token>(objToken);
            builder.Services.AddSingleton<IConnectionStringProvider>(objConstringProvider);
            builder.Services.AddScoped<ISecQueryLogon, Mdrx.PM.Server.Security.Svr.Lib.SecQueryLogon>();
            builder.Services.AddScoped<ISecQueryADIntegration, Mdrx.PM.Server.Security.Svr.Lib.SecQueryADIntegration>();
            builder.Services.AddScoped<ISecQueryUserLogonBySID, Mdrx.PM.Server.Security.Svr.Lib.SecQueryUserLogonBySID>();
            builder.Services.AddScoped<ISecQueryUserLogonBySIDInputParameters, SecQueryUserLogonBySIDInputParameters>();
            builder.Services.AddScoped<ISecQueryTenantsByLogon, Mdrx.PM.Server.Security.Svr.Lib.SecQueryTenantsByLogon>();
            builder.Services.AddScoped<ISecQueryShieldInfo, Mdrx.PM.Server.Security.Svr.Lib.SecQueryShieldInfo>();
            builder.Services.AddScoped<ISecGetShieldInfo, SecGetShieldInfo>();
            builder.Services.AddScoped<IAPMShieldAuthentication, APMShieldAuthentication>();

            builder.Services.AddScoped<IUserInformation, UserInformation>();
            builder.Services.AddScoped<IAPMADIntegrationAndSID, APMADIntegrationAndSID>();

            builder.Services.AddScoped<PersistedGrantStoreExtension>();
            builder.Services.AddScoped<ISecUpdatePersistedGrant, SecUpdatePersistedGrant>();
            builder.Services.AddScoped<ISecGetPersistedGrant, SecGetPersistedGrant>();
            builder.Services.AddScoped<ISecQueryPersistedGrant, SecQueryPersistedGrant>();
            builder.Services.AddScoped<ISecGetPersistedGrant, SecGetPersistedGrant>();

            ISecGetTenants objSecGetTenants = new Mdrx.PM.Server.Security.IO.Lib.SecGetTenants(new SqlDataAccess());
            IQueryScopes objScopeQuery = new Mdrx.PM.Server.Security.Svr.Lib.SecQueryScopes(objSecGetTenants);
            Logger.LogDebug($"Will do scope reading.");
            List<string> lstScopes = null;
            try
            {
                lstScopes = new AllscriptsPM.ScopeReader(objScopeReaderLogger, objToken, objScopeQuery).GetScopes();
                
            }
            catch (Exception e)  
            {
                Logger.LogError(e.Message);
                Logger.LogError(e.StackTrace);
                return;
            }

Based on the entries in the logging file, this is the error that we are seeing:

2023-10-21 00:00:05.415 -05:00 [DBG] [Correlation Id: ] Hosting shutdown
2023-10-21 00:00:30.410 -05:00 [DBG] [Correlation Id: ] Initializing Identity Server...
2023-10-21 00:00:30.479 -05:00 [DBG] [Correlation Id: ] SecurityDb connecting to 'Provider=msoledbsql;Data Source=tcp:ALLSCRIPTSSERVER.PEC.local;Initial Catalog=Ntier_Security;Trusted_Connection=yes;'...
2023-10-21 00:00:30.510 -05:00 [DBG] [Correlation Id: ] Will do scope reading.
2023-10-21 00:00:45.308 -05:00 [ERR] [Correlation Id: ] 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 - No such host is known.)
2023-10-21 00:00:45.341 -05:00 [ERR] [Correlation Id: ]    at System.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)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   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.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Mdrx.PM.Server.SharedSource.DataAccess.GetSqlConnection(String connectionString)
   at Mdrx.PM.Server.SharedSource.DataAccess.ExecuteReaderVb6(String connectionString, CommandType commandType, String commandText, List`1 parameters)
   at Mdrx.PM.Server.SharedSource.SqlDataAccess.ExecuteReaderVb6(IToken token, CommandType commandType, String commandText, List`1 parameters, Int32 commandTimeout, TargetDBS targetDBS)
   at Mdrx.PM.Server.Security.IO.Lib.SecGetTenants.GetData(Object vntToken, Object vntIn, Object& vntData, Int32& lngCount, Object& vntErrorInfo, Object objNonMTSConnection, Object vntOptions)
   at Mdrx.PM.Server.Security.Svr.Lib.SecQueryScopes.QueryEx(IToken token)
   at Mdrx.PM.IdentityService.AllscriptsPM.ScopeReader.GetScopes() in C:\tfsagent\vsts-agent-win-x64-2.217.2\_work\1\s\Mdrx.PM\Server\Microservices\Identity\Microservice\AllscriptsPM\ScopeReader.cs:line 62
   at Mdrx.PM.IdentityService.Startup.ConfigureServices(IServiceCollection services) in C:\tfsagent\vsts-agent-win-x64-2.217.2\_work\1\s\Mdrx.PM\Server\Microservices\Identity\Microservice\Startup.cs:line 180

I have checked that the gMSA user account has appropriate permissions in SQL Server instance, firewall settings are disabled on the application server that hosts the Docker container, that TCP/IP settings are set up correctly for that SQL instance in SQL Server configuration manager.

I just donā€™t know where else to look, as I have searched on the internet for this SQL error, and they all point to the usual places to look for and adjust settings, and I have gone through those places and verified all settings look good.

Best regards.

Iā€™m not sure how I could help. It still has nothing to do with Docker, at least you havenā€™t shared any Docker-related code or error message.

Although I had a very little experience with dotNET, it is not likely I would be able to help just by reading your dotNET source code.

I donā€™t even know the usual places so it would be helpful if you could share what you tried which you know, didnā€™t work so nobody will suggest doing the same.

If you can share any Docker related code, there is a better chance that I or anyone will have an idea.

Hi Akos,

Here is an update. It turns out that the server where the issue was happening did not have the permissions for property PrincipalsAllowedToRetrieveManagedPassword under the gmsa account. Once the server was added, the issue was resolved.

Thanks.

1 Like

Thank you for coming back and sharing the solution!