0
votes

Is it possible to connect to SQL Server Express (localdb) from a container instance?

docker-compose sample connection string:

foo-api:
  image: foo-api
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ConnectionStrings:DefaultConnection=Server=host.docker.internal\\mssqllocaldb;Database=FooDB;MultipleActiveResultSets=true;User Id=foo;Password=Your_password123;        
    build:
      context: ../ms-foo/src/
      dockerfile: Dockerfile
    ports:
      - "6004:6004"

Running the app @ localhost wtih this config works just fine:

"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=FooDB;MultipleActiveResultSets=true;User Id=foo;Password=Your_password123;"
},

Is there some dns resolution I'm missing or does the instance need to be shared somehow?

https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/sql-server-express-localdb?view=sql-server-ver15#shared-instances-of-localdb?

Update

Including the error message.

{ "error": "14 UNAVAILABLE: 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: SQL Network Interfaces, error: 25 - Connection string is not valid)"}

2
what is the error of foo-api? do you get a timeout? - castel

2 Answers

0
votes

You can reach the parent host on the container's network gateway.

Let's say your container address is 172.21.0.2. In that case, you can most likely find the SQL server at 172.21.0.1 (and the correspondent listening port).

To find out the container's IP, you can try to jump into it and print its network config, i.e. docker exec <container name> ip a, but often ip and ifconfig commands are not installed, so I'd suggest looking at the bottom of docker inspect <container name>. Keys IPAddress and Gateway hold the discussed values.

You can then build your container with a custom /etc/hosts, or point it to DNS server that can resolve this, so you can use nice names instead of IP addresses.

0
votes

I think that your error related to the environment variable defined on your docker-compose file , the second variable must be like that:

variable_name="value2"

So for your case must be like that:


DB_CONNECTION_STRING="ConnectionStrings:DefaultConnection"
DB_SERVER="host.docker.internal\\mssqllocaldb"
DB_NAME="FooDB"
DB_MultipleActiveResultSets=true
DB_USER_ID="foo"
DB_PASSWORD="Your_password123"

after that you can use this env variables to define your connection:

"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=FooDB;MultipleActiveResultSets=true;User Id=foo;Password=Your_password123;"
},

I hope that can help you to resolve your issue.