Denis Bredikhin
Denis Bredikhin

Reputation: 131

Can't connect to Azure SQL Database from Azure Container Instances

I've built a Windows container with my app inside and ran it locally. The app in the container connects to an Azure SQL Database, using the domain name from the connection string. SQL Server is configured to accept clients from any IP and from Azure Services.

Everything works fine locally. But when I run my container in Azure Container Instances, I get the following standard error:

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 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)

Upvotes: 1

Views: 6363

Answers (2)

Brandon Olin
Brandon Olin

Reputation: 412

I've experienced a similar issue with a Windows container in ACI trying to connect to an Azure SQL database. For some reason, DNS was not working inside the container. I could not resolve any public DNS names. Inside the container, DNS was pointed to a 10.x.x.x address. I never set this as part of the image build so I assume ACI is setting this as part of DHCP.

To fix this I ran the following as part of my PowerShell entrypoint script:

$nic = Get-NetAdapter
Set-DnsClientServerAddress -InterfaceIndex $nic.IfIndex -ServerAddresses ('1.1.1.1','8.8.8.8')

Upvotes: 0

Leyshon
Leyshon

Reputation: 111

You need to create a managed identity https://learn.microsoft.com/en-us/azure/container-instances/container-instances-managed-identity and grant that identity permission to the SQL database.

You can then use the Microsoft.Azure.Services.AppAuthentication library to get an access token and use it during authentication. This is only available in dotnetcore 2.2 and .net 4.6 and above.

string connectionString = "Data Source=<AZURE-SQL-SERVERNAME>; Initial Catalog=<DATABASE>;";
SqlConnection conn = new SqlConnection(connectionString);
conn.AccessToken = (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/").Result;
conn.Open();

More info can be found in the below links. None of them are explicitly for ACI but it should be basically the same from a code perspective once you have created the MSI.

https://learn.microsoft.com/en-us/azure/key-vault/service-to-service-authentication https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-sql https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi

Upvotes: 1

Related Questions