繁体   English   中英

连接到 Docker 容器中的 mongodb

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

我正在尝试将我的 web api 部署到 docker 容器。 我能够让服务在 docker 中运行,但任何与进行数据库调用相关的事情都会失败。 我不完全确定为什么。 这是我的代码:

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

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

错误

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)

如果你的 dockerized webserver 和你的数据库在同一个 docker 网络中,它们不能使用localhost相互通信,而是使用各自的服务名称。

例如而不是使用

localhost:27017

你必须使用

mongo:27017

您需要在您的 dotnet 应用程序中配置它,之后它将能够在 dockerized 设置中连接到您的数据库。 当然,您随后必须考虑您的应用程序未运行 dockerized 的情况,例如在本地开发中。 您需要一种根据当前环境(dev、docker-prod 等)设置数据库 url 的配置机制。

暂无
暂无

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

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