I have a .NET application that’s trying to connect to a SQL Server instance running in a Docker container. I’m using Docker Compose to manage my services, which include my .NET application and SQL Server.
Here’s the relevant part of my docker-compose.yml
:
version: '3.4'
services:
producttest2git:
build:
context: .
dockerfile: ProductTest2Git/Dockerfile
networks:
- myAppNetwork
SqlServerDb:
container_name: SqlServerContainer
image: mcr.microsoft.com/mssql/server:2019-latest
ports:
- 8002:1433
environment:
- ACCEPT_EULA=Y
- MSSQL_SA_PASSWORD=Admin0147
networks:
- myAppNetwork
WebApi:
container_name: producttest2gitcontainer
image: producttest2git
ports:
- 8001:80
build:
context: .
dockerfile: ProductTest2Git/Dockerfile
depends_on:
- SqlServerDb
networks:
- myAppNetwork
networks:
myAppNetwork:
And here’s my connection string
:
"ConnectionStrings": {
"DefaultConnection": "Server=SqlServerDb;Database=ProjectTestGit2; User Id=sa;Password=Admin0147;"
}
When I try to connect to SQL Server from my .NET application for example, I get the following error:
Microsoft.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)
I’ve tried the following things but none of them worked:
1- Checked the server name in the connection string.
2- Ensured that the SQL Server Docker container is running.
3- Checked that all services are on the same Docker network.
4- Checked firewall rules.
5- Tried using Entity Framework Core migrations to create the database.
6- I Can access SQL SERVER management studio using User ID as (sa) and the password as (Admin0147) and server name (localhost, 8002)
Any help would be appreciated!
2
Answers
I found a solution and it works fine at both running migrations and dealing with requests from endpoints, I used the host machine’s IP address. I'm running the SQL Server on my host machine and trying to access it from a Docker container so I modified my connection string to be like that:
"DefaultConnection": "Server=192.139.1.7,8002;Database=ProjectTestGit2; User Id=sa;Password=Admin0147;Trust Server Certificate=True"
The names of a docker compose services, e.g.
SqlServerDb
, are generally not known outside the service and are not the same as hostnames. They are basically just identifier inside the compose file, e.g. if you usedepends_on
(very simply put, refer to the Services element in the Docs for advancded infos).This is the reason why
Server=SqlServerDb
can’t connect to the DB.You could either use
Server=localhost
here, which would be the preferred method, or set a hostname for theSqlServerDb
service.