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

3

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;"
sql-server
docker
.net-core
docker-compose
containers
asked on Stack Overflow Feb 16, 2019 by Pim • edited Feb 16, 2019 by Aravind

1 Answer

0
  1. Try another port because it can cause a conflict with an existing one. e.g. "1433:1401";
  2. Disable your antivirus for a while and see if it works;
  3. Create a catalog with the name "ProductService" like defined in your appSettings.json before run the container;

I have not tested this. Try at your own risk.

answered on Stack Overflow Jun 18, 2019 by CoderMan

User contributions licensed under CC BY-SA 3.0