I’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
somebody tell me how to forward 27017 to 27018 or 27019 without getting this error I’m getting this error in every container that is not 27017
3
Answers
add this line to your docker-compose under your DB ports
for example
for example, my favorite port is 27020
Regarding ports, there are many reasons you are getting error.
1- your app’s error log shows you are trying to connect to the wrong port, "27015".
2- your overriding compose file is ending with an extra "r", thus" default "docker compose up" does not read it unless you use "-f" flag
3- if containers use the same docker network, then they will see each other running at port "27017" with their internal docker IPs, not your host forwarded ports "27018/27019". see, they are still not "27015".
PS: the solution you provided above works but you have to remember every single port change you made and edit your files all the time if you change again. that is not feasible. you need to have a "production" and "development" environment files to run your app where you set ports once and they would just work.
you must change
"mongodb://localhost:27017"
to
"mongodb://catalogcategorydb:27017"
in appsettings.json