Asp.net mongo db 'System.TimeoutException: A timeout occurred after 30000ms' in docker compose

'm getting this error in my asp.API docker-compose logs

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
  An unhandled exception has occurred while executing the request.
  System.TimeoutException: A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : "1", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/catalogcommentdb:27015" }", EndPoint: "Unspecified/catalogcommentdb:27015", ReasonChanged: "Heartbeat", State: "Disconnected", ServerVersion: , TopologyVersion: , Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server.
   ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (111): Connection refused 172.24.0.4:27015
     at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
     at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
     at MongoDB.Driver.Core.Connections.TcpStreamFactory.Connect(Socket socket, EndPoint endPoint, CancellationToken cancellationToken)
     at MongoDB.Driver.Core.Connections.TcpStreamFactory.CreateStream(EndPoint endPoint, CancellationToken cancellationToken)
     at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelper(CancellationToken cancellationToken)
     --- End of inner exception stack trace ---
     at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelper(CancellationToken cancellationToken)
     at MongoDB.Driver.Core.Connections.BinaryConnection.Open(CancellationToken cancellationToken)
     at MongoDB.Driver.Core.Servers.ServerMonitor.InitializeConnection(CancellationToken cancellationToken)
     at MongoDB.Driver.Core.Servers.ServerMonitor.Heartbeat(CancellationToken cancellationToken)", LastHeartbeatTimestamp: "2022-08-08T12:28:13.2001516Z", LastUpdateTimestamp: "2022-08-08T12:28:13.2001518Z" }] }.
     at MongoDB.Driver.Core.Clusters.Cluster.ThrowTimeoutException(IServerSelector selector, ClusterDescription description)
     at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChangedHelper.HandleCompletedTask(Task completedTask)
     at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChanged(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken)
     at MongoDB.Driver.Core.Clusters.Cluster.SelectServer(IServerSelector selector, CancellationToken cancellationToken)
     at MongoDB.Driver.MongoClient.AreSessionsSupportedAfterServerSelection(CancellationToken cancellationToken)
     at MongoDB.Driver.MongoClient.AreSessionsSupported(CancellationToken cancellationToken)
     at MongoDB.Driver.MongoClient.StartImplicitSession(CancellationToken cancellationToken)
     at MongoDB.Driver.OperationExecutor.StartImplicitSession(CancellationToken cancellationToken)
     at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSession[TResult](Func`2 func, CancellationToken cancellationToken)
     at MongoDB.Driver.MongoCollectionImpl`1.FindSync[TProjection](FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
     at MongoDB.Driver.FindFluent`2.ToCursor(CancellationToken cancellationToken)
     at MongoDB.Driver.IAsyncCursorSourceExtensions.Any[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
     at MongoDB.Driver.IFindFluentExtensions.Any[TDocument,TProjection](IFindFluent`2 find, CancellationToken cancellationToken)
     at CatalogComment.API.Data.CatalogCommentContextSeed.SeedData[T](IMongoCollection`1 productCollection, List`1 seedData) in /src/Services/CatalogComment/CatalogComment.API/Data/CatalogCommentContextSeed.cs:line 9
     at CatalogComment.API.Data.CatalogCommentContext..ctor(IConfiguration configuration) in /src/Services/CatalogComment/CatalogComment.API/Data/CatalogCommentContext.cs:line 16
     at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
     at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
     at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
     at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
     at lambda_method9(Closure , IServiceProvider , Object[] )
     at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
     at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
  --- End of stack trace from previous location ---
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
     at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
     at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
     at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
     at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
     at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

and this is my docker-compose.yml

   version: '3.4'

services:
  catalogdb:
    image: mongo

  catalogbranddb:
    image: mongo

  catalogcategorydb:
    image: mongo

  catalog.api:
    image: ${DOCKER_REGISTRY-}catalogapi
    build:
      context: .
      dockerfile: Services/Catalog/Catalog.API/Dockerfile

  catalogbrand.api:
    image: ${DOCKER_REGISTRY-}catalogbrandapi
    build:
      context: .
      dockerfile: Services/CatalogBrand/CatalogBrand.API/Dockerfile


  catalogcategory.api:
    image: ${DOCKER_REGISTRY-}catalogcategoryapi
    build:
      context: .
      dockerfile: Services/CatalogCategory/CatalogCategory.API/Dockerfile

and this is my docker-compose-overider.yml

version: '3.4'

services:

  catalogdb:
    container_name: catalogdb
    restart: always
    ports:
        - "27017:27017"
    volumes:
        - ./mongo_data_catalogdb:/data/catalogdb

  catalogcategorydb:
    container_name: catalogcategorydb
    restart: always
    ports:
        - "27018:27017"
    volumes:
        - ./mongo_data_catalogcategorydb:/data/catalogcategorydb

  catalogbranddb:
    container_name: catalogbranddb
    restart: always
    ports:
        - "27019:27017"
    volumes:
        - ./mongo_data_catalogbranddb:/data/catalogbranddb

  catalog.api:
    container_name: catalog.api
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - "DatabaseSettings:ConnectionString=mongodb://catalogdb:27017"
      - "ElasticConfiguration:Uri=http://elasticsearch:9200"
    depends_on:
      - catalogdb
    ports:
      - "8000:80"

  catalogbrand.api:
    container_name: catalogbrand.api
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - "DatabaseSettings:ConnectionString=mongodb://catalogbranddb:27019"
      - "ElasticConfiguration:Uri=http://elasticsearch:9200"
    depends_on:
      - catalogbranddb
    ports:
      - "8001:80"

  catalogcategory.api:
    container_name: catalogcategory.api
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - "DatabaseSettings:ConnectionString=mongodb://catalogcategorydb:27018"
      - "ElasticConfiguration:Uri=http://elasticsearch:9200"
    depends_on:
      - catalogcategorydb
    ports:
      - "8002:80"

I’m getting this error in all of the APIs Except Catalog.API and only catalog.API worked perfectly and I tried to do everything that I did with Catalog.API but still show error for other services and these are my container

your are getting “Connection refused 172.24.0.4:27015”. if you look closely, you will see you are trying to connect port “27015” but your container has only “27017/27018/27019”.

whenever you get a “timeout/refused”, always check the connection string and then the security IP access list. and if you get a “drop”, check credentials and user access list.

1 Like

I found my answer here CLICK HERE

what you have added to your compose file is just telling to run mongodb on another port “of container”, but then your port mapping is still wrong because it is “outsideport:insideport” and the command changes “insideport” not “outsideport”

You are making things a bit harder for future uses than you can imagine. What you think you have corrected is not valid “in terms of ports”. It is like pushing all the action buttons to get a combo move in that game, it may work but that does not mean you have solved the main issue.

There are 2 reasons, that I missed one before:

  • your app tries to connect to port “27015” according to your error messages where there is no server listening on. if all containers are connected via same internal network, then they need to use “27017” default port. If you use external IPs, then they have to use “27017/27018/27019” of the server they try to use.
  • your overriding compose file has an extra tailing “r”, thus it is not even read by composer with default “docker compose up” command unless you are using “-f” flags each time to read these files.