2025/02/21

[ASP.NET Core] 解決如何從 Docker Container 連至本機的 SQL Server

markdown ### 問題 在 Visual Studio 開發 ASP.NET Core 網站以 IIS Express 啟動時可正確連線 SQL Server 的資料庫。 近期改以 Docker 來啟動網站時,出現以下錯誤訊息:
SqlException: 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)
### 開發環境 - Visual Studio 2022 v17.12.4 - Docker Desktop v4.38.0 - ASP.NET Core (.NET 8) ### 解決方法 原本的連線字串: ``` Server=localhost;Database=MyWebDB;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True; ``` 1. 確認 SQL Server Browser 的服務為啟用 2. 確認 SQL SERVER 的 TCP/IP 是否有開啟 3. 確認防火牆 1433 的連接埠是否開啟 (若本機連線的話可不用對外開放) 4. 把原本連線字串的 Server=localhost 的部分改成 Server=`host.docker.internal,1433` 並採用帳號密碼的方式連線 修改後的連線字串如下: ``` Server=host.docker.internal,1433;Database=MyWebDB;User Id=mydb-user;Password=mydb-password;MultipleActiveResultSets=true;TrustServerCertificate=True; ``` ### 參考連結 - Cannot connect to SQL server from a docker container with .Net 6 - SQL Server Configuration Manager

沒有留言:

張貼留言