Home > other >  Access From an API in container A to a SQL server in docker container B
Access From an API in container A to a SQL server in docker container B

Time:01-05

I try to have my project containerized but encounter an issue I cant get my head around.

What I do:

  1. Create a network => docker network create Network-Dev
  2. Create a SQL server on the network (port 1440) => docker run --hostname SQL-server --network Network-Dev -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=passwordsAreOverrated@dev2023" -e "MSSQL_PID=Express" -p 1440:1433 -d --name dev-SQL -v //c/mount/sql:/var/opt/mssql/data mcr.microsoft.com/mssql/server:latest
  3. Create API on network => docker run --rm --name Dev-API --network Network-Dev -p 5000:80 api-dev

What happens: The Network is created, the SQL server is running (and accessible on the host machine by SSMS on 127.0.0.1,1440)

BUT => When the API tries to connect to the SQLserver it gets an error => using connectionstring "Server=SQL-server,1440; User Id=sa; Password=passwordsAreOverrated@dev2023; Trusted_Connection=True;TrustServerCertificate=true;Integrated Security=false;"

Error from .Net application: Microsoft.Data.SqlClient.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: Could not open a connection to SQL Server)'

When inspecting the network via docker (docker network inspect Network-Dev) I see the network as bridge with the two containers.

I would like to understand what I am missing here and if it is possible even a sollution to the problem ;)

Thanx for reading all of this!

CodePudding user response:

On the Docker network, you use the unmapped port numbers, so you should use port 1443. Since that's the default, you can leave it out in your connection string:

Server=SQL-server; User Id=sa; Password=passwordsAreOverrated@dev2023; Trusted_Connection=True;TrustServerCertificate=true;Integrated Security=false;

You only need to map the port to a host port if you need to access it from the host. If you only need to access the SQL server from the API container, you don't need to map the SQL server port.

  • Related