简体   繁体   English

连接到 Docker 容器中的 mongodb

[英]Connecting to a mongodb thats within a Docker container

I am trying to deploy my web api to a docker container.我正在尝试将我的 web api 部署到 docker 容器。 I am able to get the service running in docker but anything related to making a database call it falls over.我能够让服务在 docker 中运行,但任何与进行数据库调用相关的事情都会失败。 I'm not entirely sure why.我不完全确定为什么。 Here is my code:这是我的代码:

Dockerfile_local Dockerfile_local

FROM mcr.microsoft.com/dotnet/core/sdk:3.1.302-alpine3.12 as builder
EXPOSE 27017

COPY . .

RUN dotnet publish --configuration Release MembershipApi/MembershipApi.csproj -o /app

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1.8-alpine3.12

WORKDIR /app

COPY --from=builder /app .

CMD ["dotnet", "MembershipApi.dll"]

docker-compose-local.yml docker-compose-local.yml

version: "3"
services: 
    test:
        image: mcr.microsoft.com/dotnet/core/sdk:3.1.402-alpine3.12
        depends_on: 
            - membership-api
            - mongo
        entrypoint: ["dotnet","test", "/builds/MembershipApi.IntergrationTests/MembershipApi.IntergrationTests.csproj", "--configuration", "Release"]
        volumes:
            - .:/builds
        
    membership-api:
        build:
            context: .
            dockerfile: Dockerfile_local
        depends_on:
            - mongo
        ports:
            - 9000:80
    mongo:
        image: mongo:4.0.16
        ports:
            - 27017

Error错误

membership-api_1  | warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
membership-api_1  |       Failed to determine the https port for redirect.
membership-api_1  | fail: Microsoft.AspNetCore.Server.Kestrel[13]
membership-api_1  |       Connection id "0HM3LNKLS24AA", Request id "0HM3LNKLS24AA:00000002": An unhandled exception was thrown by the application.
membership-api_1  | System.TimeoutException: A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "Automatic", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : 
"Unspecified/localhost:27017" }", EndPoint: "Unspecified/localhost:27017", ReasonChanged: "Heartbeat", State: "Disconnected", ServerVersion: , TopologyVersion: , Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server.
membership-api_1  |  ---> System.Net.Sockets.SocketException (99): Address not available
membership-api_1  |    at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)
membership-api_1  |    at System.Net.Sockets.Socket.ConnectAsync(EndPoint remoteEP)
membership-api_1  |    at MongoDB.Driver.Core.Connections.TcpStreamFactory.ConnectAsync(Socket socket, EndPoint endPoint, CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.Core.Connections.TcpStreamFactory.CreateStreamAsync(EndPoint endPoint, CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancellationToken)
membership-api_1  |    --- End of inner exception stack trace ---
membership-api_1  |    at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.Core.Servers.ServerMonitor.InitializeConnectionAsync(CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.Core.Servers.ServerMonitor.HeartbeatAsync(CancellationToken cancellationToken)", LastHeartbeatTimestamp: "2020-10-21T12:31:43.5254072Z", LastUpdateTimestamp: "2020-10-21T12:31:43.5254077Z" }] }.
membership-api_1  |    at MongoDB.Driver.Core.Clusters.Cluster.ThrowTimeoutException(IServerSelector selector, ClusterDescription description)
membership-api_1  |    at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChangedHelper.HandleCompletedTask(Task completedTask)
membership-api_1  |    at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChanged(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.Core.Clusters.Cluster.SelectServer(IServerSelector selector, CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.MongoClient.AreSessionsSupportedAfterServerSelection(CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.MongoClient.AreSessionsSupported(CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.MongoClient.StartImplicitSession(CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.OperationExecutor.StartImplicitSession(CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSession[TResult](Func`2 func, CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.MongoCollectionImpl`1.FindSync[TProjection](FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.FindFluent`2.ToCursor(CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.IAsyncCursorSourceExtensions.SingleOrDefault[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
membership-api_1  |    at MongoDB.Driver.IFindFluentExtensions.SingleOrDefault[TDocument,TProjection](IFindFluent`2 find, CancellationToken cancellationToken)
membership-api_1  |    at MembershipApi.Data.PaymentRepo.GetBalanceById(Int32 id) in /MembershipApi/Data/PaymentRepo.cs:line 23
membership-api_1  |    at MembershipApi.Controllers.PaymentController.GetBalance(Int32 id) in /MembershipApi/Controllers/PaymentController.cs:line 24
membership-api_1  |    at lambda_method(Closure , Object , Object[] )
membership-api_1  |    at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
membership-api_1  |    at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)     
membership-api_1  |    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
membership-api_1  |    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
membership-api_1  |    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
membership-api_1  | --- End of stack trace from previous location where exception was thrown ---
membership-api_1  |    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
membership-api_1  |    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
membership-api_1  |    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
membership-api_1  | --- End of stack trace from previous location where exception was thrown ---
membership-api_1  |    at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
membership-api_1  |    at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
membership-api_1  |    at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
membership-api_1  |    at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
membership-api_1  |    at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

If both your dockerized webserver and your database are in the same docker network, they can't communicate with each other using localhost but with their respective service name.如果你的 dockerized webserver 和你的数据库在同一个 docker 网络中,它们不能使用localhost相互通信,而是使用各自的服务名称。

Eg instead of using例如而不是使用

localhost:27017

you must use你必须使用

mongo:27017

You need to configure this in your dotnet app, after that it will be able to connect to your database in the dockerized setup.您需要在您的 dotnet 应用程序中配置它,之后它将能够在 dockerized 设置中连接到您的数据库。 Of course you then have to think about cases, where your apps are not running dockerized, eg in local development.当然,您随后必须考虑您的应用程序未运行 dockerized 的情况,例如在本地开发中。 You need a configuration mechanism that sets the database url depending on the current environment (dev, docker-prod, etc.).您需要一种根据当前环境(dev、docker-prod 等)设置数据库 url 的配置机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM