I am trying to run my application in docker while also creating a SQL Server.
It does not seem to connect to my SQL Server and I get the following error:
Unhandled exception. 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: Could not open a connection to SQL Server)
This is how my docker-compose file looks like.
version: '3.7'
services:
musicapi:
build:
context: .
ports:
- 80:80
environment:
Authentication:Enabled: 'true'
restart: always
depends_on:
- testdb
testdb:
image: mcr.microsoft.com/mssql/server:2017-latest
ports:
- "1433:1433"
environment:
TZ: Europe/Amsterdam
ACCEPT_EULA: "y"
SA_PASSWORD: Password01
volumes:
- mssql_data:/var/opt/mssql/data
restart: always
volumes:
mssql_data:
And my Dockerfile:
FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:6.0 as build
WORKDIR /src
COPY . .
RUN dotnet restore
RUN dotnet build -c Release
RUN dotnet publish -c Release -o ./out
FROM base AS final
WORKDIR /app
COPY --from=build /src/out .
# The following 2 lines are required for solving:
# "Globalization Invariant Mode is not supported" error.
RUN apk add --no-cache icu-libs
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false
ENTRYPOINT ["dotnet", "Test.Api.dll"]
My connection string looks like this:
"ConnectionStrings":
{
"DefaultConnection":
"Server=localhost,1433;Database=test.db;User ID=sa;Password=Password01;TrustServerCertificate=True;"
}
What am I doing wrong?
1条答案
按热度按时间hjzp0vay1#
Each container is a separate network entity, so when your connection string specifies
Server=localhost
, that means that the database is in the same container as your application.On the Docker network that docker-compose creates, the containers can talk to each other using the service names as the host names. In your case, the database container can be reached using the host name
testdb
.So you connection string should be