我已经构建了一个 Windows 容器,其中包含我的应用程序并在本地运行它。容器中的应用程序使用连接字符串中的域名连接到 Azure SQL 数据库。 SQL Server 配置为接受来自任何 IP 和 Azure 服务的客户端。
本地一切正常。但是,当我在 Azure 容器实例中运行容器时,出现以下标准错误:
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.)
最佳答案
您需要创建托管身份 https://learn.microsoft.com/en-us/azure/container-instances/container-instances-managed-identity并向 SQL 数据库授予该身份权限。
然后,您可以使用 Microsoft.Azure.Services.AppAuthentication 库获取访问 token 并在身份验证期间使用它。这仅适用于 dotnetcore 2.2 和 .net 4.6 及更高版本。
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();
更多信息可以在下面的链接中找到。它们都不是明确用于 ACI 的,但一旦创建了 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
关于azure - 无法从 Azure 容器实例连接到 Azure SQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53777219/