🔧

WSL2 の Ubuntu から SqlConnection を使って Azure SQL Database に接続できない

に公開

ハマったのでメモします。

WSL2 上の Ubuntu で Azure SQL Database に接続する C# のプログラムを書いたところ、以下のエラーが発生しました。

System.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)

Azure SQL Database のファイアウォールは構成済みです。また、ホストの Windows や Ubuntu から sqlcmd を実行した場合は接続できます。C# のプログラムだけエラーになるという状態です。apt-get upgradewsl --update を実施しても効果はありませんでした。検索すると openssl の設定が原因という情報も見かけましたが、そちらを実施しても解決しませんでした。

最終的には /etc/resolv.conf を修正することで解決しました。

- nameserver 172.28.32.1
+ nameserver 8.8.8.8

あわせて、元に戻らないように /etc/wsl.conf も修正する必要があります。

[network]
generateResolvConf = false

Discussion