MongoDB connection timeout using dotnet core using docker-compose

Viewed 2349

I develop a WebAPI service in dotnet core 2.2. I use Docker desktop for windows with Linux containers I have this docker-compose file

version: '3.4'

services:
  mongo:
    image: mongo
    ports:
      - 27017:27017
  mongo-express:
    image: mongo-express
    ports:
      - 8088:8081
    depends_on:
      - mongo
  MyWebApi:
    image: MyWebApi
    build:
      context: .
      dockerfile: MyWebApi/Dockerfile
    ports:
      - 80:80
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=http://+:5003
    depends_on:
      - mongo

and this Dockerfile for my web api :

FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 80
#EXPOSE 443

FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /src
COPY ["TMSApi/TMSApi.csproj", "TMSApi/"]
COPY ["BusinessEntities/BusinessEntities.csproj", "BusinessEntities/"]
COPY ["TMSService/TMSService.csproj", "TMSService/"]
COPY ["TMSRepository/TMSRepository.csproj", "TMSRepository/"]
RUN dotnet restore "TMSApi/TMSApi.csproj"
COPY . .
WORKDIR "/src/TMSApi"
RUN dotnet build "TMSApi.csproj" -c Debug -o /app

FROM build AS publish
RUN dotnet publish "TMSApi.csproj" -c Debug -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "TMSApi.dll", "--environment=Development"]

In my webapi appsettings.json, i use this connection string :

mongodb://mongo:27017

In the docker-compose file i have 3 services : mongo, mongo-express and MyWebApi mongo-express is connected to mongo when i use localhost:8088.

But i have a timeout when MyWebApi try to connect to mongo service.

Do you have an idea how to fix this ? i want to keep this running inside docker containers

I found some recent articles on the subject but with no result...

Thanks

2 Answers

I resolved my problem

The web api, tried to reach the host mongotms instead of mongo (I saw this in the stacktrace). In my test yesterday morning I changed the service name and the settings from mongo to mongotms then I build the image. After I changed my mind and I rolled back my changes, rebuild the images but it kept the old mongo service name.

Your docker-compose.yml is correct and the url you are using is also correct. What I think the problem is - it takes for mongo longer time to start than to YourWebApi and you simply try to connect to database while it is not yet ready.

depends_on field only controls the start order but gives no warranty that services are ready.

So, try put some timeout in you application. If it works, just introduce wait-for method - waiting until remote socket opens. This is a standard way for solving your issue.

Related