Problem:
The challenge was to connect to an SQL Server Instance hosted inside Docker Container on the same network from another an ASP.Net Core 3.0 Application hosted inside another Docker Container running on the same network.
- Your scenario might be different from the above, however, a basic understanding of TCP/IP protocol will help you resolve most problems in IT.
- Nevertheless, every time a docker container starts an error would occur:
Unhandled exception. 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)
- Asp.Net Core 3.0 application could not establish a connection to SQL Server on same network, inspecting an SQL Server Container shows an IP address listening on 0.0.0.0: PortNumber.
- In this case, a Container hosting an Asp.Net Application sees the Network hosting SQL Server as public Network so the Firewall blocks the connection.
Solution:
- Add network_mod: host to the docker-compose.yml file under Build to allow the docker container to connect to the instances on the local machine.
version: '3'
services:
TheNameOfYourServer_CouldBeAnythingYourWant:
image: connectsqlserver
build:
context: ./ConnectSqlServer
dockerfile: Dockerfile
network_mode: host