Connection to Docker SQL Server container does not work Entity Framework Core

kuhbmx9i  于 2023-11-16  发布在  Docker
关注(0)|答案(2)|浏览(121)

Having issues with connecting to SQL Server in Docker container.

I'm using this to setup the container:

docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=********" -e "MSSQL_PID=Evaluation" -p 1433:1433  --name sqlserver --hostname sqlserver -d mcr.microsoft.com/mssql/server:2022-preview-ubuntu-22.04

This is my connection string:

"Server=localhost,1433;Database=TemplateDb;User Id=sa;Password=********;Integrated Security=false;TrustServerCertificate=true"

I'm getting this exception:

Microsoft.Data.SqlClient.SqlException: '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: Could not open a connection to SQL Server)'

Regular connection via Management Studio or Azure Data Studio to the container works fine. Database is created. I tried to restart container, I checked firewall settings, I even tried to connect via docker exec - works. In docker -ps is container running.

p8h8hvxi

p8h8hvxi1#

Dont Have enough rep to upvote on @Amit Mohanty's response. But that worked for me and saved me a headache.

My Connection string for running an sql server 2022 and connecting to it in entityframeworkcore 7.0.13, looked like this:

"Server=MyDockerContainerName,1433;Database=bookify;User Id=sa;Password=Password123!;Encrypt=false;TrustServerCertificate=true;MultipleActiveResultSets=true;"

dont use localhost use the docker container name.

p3rjfoxz

p3rjfoxz2#

You've used Server=localhost,1433 , which would refer to the local machine, not the Docker container. To connect to the SQL Server running in the Docker container, you should use the container name (or IP address) as the server name in your connection string. In your case, you've named the container sqlserver , so your connection string should look like this:

"Server=sqlserver,1433;Database=TemplateDb;User Id=sa;Password=********;Integrated Security=false;TrustServerCertificate=true"

相关问题