azure - 无法从 Azure 容器实例连接到 Azure SQL 数据库

标签 azure containers azure-sql-database azure-container-instances

我已经构建了一个 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/

相关文章:

passwords - 在 Windows Azure 中存储密码的最佳实践

c++ - 通用结束迭代器与容器的可递减要求 `end()`

azure - 何时应在 CosmosDB 中创建新容器?

sql-server - 不支持使用 CommandBehavior=SequentialAccess 检索加密列 'xxx'

azure - 如何在 Windows Azure 中创建备份

azure - 手动运行计划的 Azure WebJob

azure - 获取 azure 订阅属于什么类型例如 Pay As you Go、MCA、EA、CSP

azure - 如何确定 Azure 队列中的所有消息是否都已处理完毕?

kubernetes - 如何在一个 Kubernetes 的 pod 中实现后处理容器

azure - 不使用管理控制台确定 SQL Azure 区域