Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core API can't connect to database via docker-compose

I'm developing a .NET core web API with a MSSQL Server database. I tried to containerize this into a Docker container and use Docker Compose to spin up this service. But my API cannot connect to the database.

The following error occurs:

Application startup exception: System.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)

Code in my startup:

services.AddDbContext<ProductServiceDbContext>(options =>
     options.UseSqlServer("server=sqlserver;port=1433;user id=sa;password=docker123!;database=ProductService;"));

Dockerfile:

FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /app

COPY *.csproj ./
RUN dotnet restore dockerapi.csproj

COPY . ./
RUN dotnet publish dockerapi.csproj -c Release -o out

FROM microsoft/dotnet:2.1-aspnetcore-runtime AS runtime

WORKDIR /app

COPY --from=build /app/out .

ENTRYPOINT ["dotnet", "dockerapi.dll"]`

Docker-compose:

version: '3.4'

services:
   productservice:
     image: productservice/api
     container_name: productservice_api
     build:
       context: ./ProductService/ProductService
     depends_on:
       - sqlserver
     ports:
       - "5000:80"

   sqlserver:
     image: microsoft/mssql-server-linux:latest
     container_name: sqlserver
     ports:
       - "1433"
     environment:
       - ACCEPT_EULA=Y 
       - SA_PASSWORD=docker123!

I've tried several things:

  • Add links in the docker-compose file (sqlserver in productservice)
  • Add networks to the docker-compose file
  • Changed the connection string to "server=sqlserver;user id=sa;password=docker123!;database=ProductService;" or "server=sqlserver,1433;user id=sa;password=docker123!;database=ProductService;"
like image 823
Pim Avatar asked Feb 16 '19 11:02

Pim


1 Answers

Hey I was having a similar issue and stumbled upon your post, this was not the same issue I was having but I think I know the problem you were having (sorry this reply is so late)

Looking at your connection string server=sqlserver;port=1433;user id=sa;password=docker123!;database=ProductService;, you actually have to specify the port another way: server=sqlserver,1433;user id=sa;password=docker123!;database=ProductService;

Hope this helps!

like image 144
Mark Davies Avatar answered Nov 09 '22 23:11

Mark Davies