I’m running a .NET app and trying to dockerize it. My docker compose is as follows:
version: '3.4'
services:
mssql:
container_name: mtg-mssql-db
hostname: mssql-db
image: mcr.microsoft.com/mssql/server:2022-latest
environment:
ACCEPT_EULA: 'Y'
MSSQL_SA_PASSWORD: 'Admin@123'
MSSQL_DATA_DIR: /var/opt/mssql/data
MSSQL_PID: 'Developer'
MSSQL_TCP_PORT: 1433
ports:
- "1455:1433"
volumes:
- ./data:/var/opt/mssql/data
- ./log:/var/opt/mssql/log
- ./secrets:/var/opt/mssql/secrets
mtgmvc:
image: ${DOCKER_REGISTRY-}mtgmvc
build:
context: .
dockerfile: MTGMVC/Dockerfile
And my appsettings is:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Data Source=localhost,1455;Initial Catalog=MTGCards;User ID=sa;Password=Admin@123;Integrated Security=True",
"Redis": "host.docker.internal:5005"
}
}
I’ve reviewed the connection string and it seems good to me, but I can’t reach the database like this, am I missing some network issue with docker here?
>Solution :
The issue seems to be with the connection string in your appsettings.json. When using Docker Compose, services communicate using the service names as hostnames, not localhost. In your setup, the SQL Server service is named mssql and should be accessed as such.
So I’ll suggest you change your connection string in appsettings.json to:
"DefaultConnection": "Data Source=mssql-db,1433;Initial Catalog=MTGCards;User ID=sa;Password=Admin@123;”
This uses mssql-db (the hostname you defined for your SQL service) instead of localhost, and the correct port 1433.
You might also have to remove Integrated Security=True(if the changes above don’t work) since you’re using SQL authentication, not Windows authentication.