Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker container app cannot connect to SQL Server in Docker host

A .NET application in a Docker container (based on microsoft/dotnet-framework image) fails to connect to SQL Server 2016 installed on the Docker host system. The Docker host is Windows Server 2016. Docker version is 17.03.2-ee-5.

I run the container and .NET application using the command sequence:

docker run -it microsoft/dotnet-framework cmd
docker cp App <container-id>:/
docker exec -it <container-id> cmd
cd App
TestConn.exe

TestConn.exe throws an exception after ~10 seconds, complaining that it cannot connect to SQL Server. The connection string is:

Data Source=localhost;Initial Catalog=SomeDB;Persist Security Info=False;User ID=appuser;Password=apppwd;MultipleActiveResultSets=False;Connection Timeout=30;

If I run TestConn.exe in the Docker host system, the application connects to SQL Server successfully.

I added --expose=1433 to the docker run command - did not work. The way I expect this to work is that TestConn.exe attempts a connection to localhost (default SQL port 1433), which in turn connects to the port 1433 in the Docker host, which corresponds to SQL Server.

like image 236
Web User Avatar asked Aug 23 '17 00:08

Web User


People also ask

Can docker container Access database on host?

You can also access the MySQL service running in your host machine in your Docker container using the bridge network mode. For that, you need to ensure that the MySQL service is actively listening for all the connections in the 172.17. 42.1 address.

Can I run SQL Server in a docker container?

With Docker, you can also run multiple SQL Server Containers on the same host machine. You can use this approach for situations that need multiple instances of SQL Server on the same host. Every container needs to expose itself to a different port.


1 Answers

The feature you are looking for does exist, the ip is "host.docker.internal", you can substitute "localhost" by that and the app will be able to connect to the DB running in another of your docker containers.

This is available only from version 18.03 onwards and for Mac and Windows (no support for Linux on this one yet...). In Linux "Use --net="host" in your docker run command, then localhost in your docker container will point to your docker host."

How to access host port from docker container has more information on this.

like image 168
eat chocolate Avatar answered Sep 18 '22 18:09

eat chocolate