Cieja Cieja - 3 years ago 250
Linux Question

Microsoft SQL Server on Linux (docker) - connection refused

I'm trying to connect from my Asp.Net Core app to my MSSQL which I run using docker, but I'm getting an error message:


"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: 35 - An internal exception was caught)"


Here's my docker compose:

api:
image: api
container_name: api
build:
context: ./Api
dockerfile: Dockerfile
ports:
- "8000:80"
depends_on:
- db
db:
image: "microsoft/mssql-server-linux"
container_name: mssql
environment:
SA_PASSWORD: "YourStrong!Passw0rd"
ACCEPT_EULA: "Y"
MSSQL_PID: "Developer"
ports:
- "127.0.0.1:8001:1433"


and appsettings.json:

{
"ConnectionStrings": {
"DefaultConnection": "server=127.0.0.1,8001;database=MyTestDb;user=sa;password=YourStrong!Passw0rd"
}
}


Connection via SSMS works well, but when in my code I try to use:

Database.EnsureCreated();


I'm getting an error which I described upper.

Do you know how can I handle this problem?

Answer Source

Your issue is the connection string

{
  "ConnectionStrings": {
    "DefaultConnection": "server=127.0.0.1,8001;database=MyTestDb;user=sa;password=YourStrong!Passw0rd"
  }
}

In docker-compose container to container networking you are concerned about container service name and ports exposed in container itself. You don't want to consider the host port mapping from inside the container. Use below connection string

{
  "ConnectionStrings": {
    "DefaultConnection": "server=db, 1433;database=MyTestDb;user=sa;password=YourStrong!Passw0rd"
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download