简体   繁体   English

docker-compose 应用程序容器无法连接到 mongo 容器

[英]docker-compose app container can't connect to mongo container

I'm trying to run my dotnet core project and mongodb as container services with docker-compose .我正在尝试使用docker-compose将我的 dotnet 核心项目和 mongodb 作为容器服务运行。 Both services have a clean start with no errors.这两种服务都有一个干净的开始,没有错误。 When I call an endpoint that interacts with mongo I get a timeout error.当我调用与 mongo 交互的端点时,出现超时错误。 Since I'm using docker-compose I expect that I can reference the mongo service by the compose service name in the connection string.由于我使用的是docker-compose我希望我可以通过连接字符串中的 compose 服务名称来引用mongo服务。

mongo:27017/api?authSource=api with username api and password password123 as seen in the docker-compose file below. mongo:27017/api?authSource=api用户名api和密码password123如下面的 docker-compose 文件所示。 Instead I get this error:相反,我收到此错误:

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/mongo:27017" }", EndPoint: "Unspecified/mongo:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server.
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (00000005, 0xFFFDFFFF): Name or service not known
   at System.Net.Dns.InternalGetHostByName(String hostName)
   at System.Net.Dns.ResolveCallback(Object context)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Dns.HostResolutionEndHelper(IAsyncResult asyncResult)
   at System.Net.Dns.EndGetHostAddresses(IAsyncResult asyncResult)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
   at MongoDB.Driver.Core.Connections.TcpStreamFactory.ResolveEndPointsAsync(EndPoint initial)
   at MongoDB.Driver.Core.Connections.TcpStreamFactory.CreateStreamAsync(EndPoint endPoint, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Servers.ServerMonitor.HeartbeatAsync(CancellationToken cancellationToken)", LastUpdateTimestamp: "2020-09-03T21:28:59.1614966Z" }] }.
  Stack Trace:
     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.WaitForDescriptionChangedAsync(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Clusters.Cluster.SelectServerAsync(IServerSelector selector, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoClient.AreSessionsSupportedAfterSeverSelctionAsync(CancellationToken cancellationToken)
   at MongoDB.Driver.MongoClient.AreSessionsSupportedAsync(CancellationToken cancellationToken)
   at MongoDB.Driver.MongoClient.StartImplicitSessionAsync(CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionBase`1.DeleteOneAsync(FilterDefinition`1 filter, DeleteOptions options, Func`2 bulkWriteAsync)
   at Tests.AssetRespositoryTest.DeleteAsset(String assetId) in /app/Tests/Repository/AssetRepositoryTests.cs:line 140
   at Tests.AssetRespositoryTest.TestWithTransaction() in /app/Tests/Repository/AssetRepositoryTests.cs:line 75
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__139_0(Object state)

I've confirmed my connection string has the user/pass set to what's in the compose file below.我已经确认我的连接字符串将用户/密码设置为下面的撰写文件中的内容。 If I exec into my app container I can ping the mongo container by service name, but I can't use the mongo shell to connect with the root or api user instead I get this error from the mongo shell:如果我exec进入我的应用程序容器,我可以通过服务名称 ping mongo容器,但我不能使用 mongo shell 与rootapi用户连接,而是从 mongo shell 收到此错误:

docker-compose exec app bash
mongo --host mongo --port 27017 -u api -p password123 --authenticationDatabase api

2020-09-03T20:28:37.209+0000 E QUERY    [js] Error: couldn't connect to server mongo:27017, connection attempt failed: SocketException: Error connecting to mongo:27017 (23.217.138.110:27017) :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:344:17

Interestingly I can connect when running the same mongo shell connect command from my host terminal so this seems to be a container issue.有趣的是,我可以在从我的主机终端运行相同的 mongo shell connect 命令时进行连接,所以这似乎是一个容器问题。

docker-compose.yml docker-compose.yml

version: '2'

networks:
  # This special network is configured so that the local metadata
  # service can bind to the specific IP address that ECS uses
  # in production
  credentials_network:
      driver: bridge
      ipam:
          config:
              - subnet: "169.254.170.0/24"
                gateway: 169.254.170.1

services:
  # This container vends credentials to your containers
  ecs-local-endpoints:
    # The Amazon ECS Local Container Endpoints Docker Image
    image: amazon/amazon-ecs-local-container-endpoints
    volumes:
      # Mount /var/run so we can access docker.sock and talk to Docker
      - /var/run:/var/run
      # Mount the shared configuration directory, used by the AWS CLI and AWS SDKs
      # On Windows, this directory can be found at "%UserProfile%\.aws"
      - ${USERPROFILE}\\.aws:/home/.aws/
    environment:
      # define the home folder; credentials will be read from $HOME/.aws
      HOME: "/home"
      # You can change which AWS CLI Profile is used
      AWS_PROFILE: "default"
    networks:
        credentials_network:
            # This special IP address is recognized by the AWS SDKs and AWS CLI 
            ipv4_address: "169.254.170.2"

  app:
    depends_on:
      - ecs-local-endpoints
      - mongo
    networks:
      credentials_network:
        ipv4_address: "169.254.170.3"
    build: 
      context: .
      dockerfile: 'Dockerfile.compose'
    environment:
      ASPNETCORE_ENVIRONMENT: "local"
      AWS_DEFAULT_REGION: "us-east-1"
      AWS_CONTAINER_CREDENTIALS_RELATIVE_URI: "/creds"
    volumes:
      - './:/app'
    links:
      - mongo:mongo
    ports:
      - 9999:9999

  mongo:
    image: 'bitnami/mongodb:4.2'
    restart: 'always'
    environment:
      - MONGODB_ROOT_PASSWORD=iamroot
      - MONGODB_USERNAME=api
      - MONGODB_PASSWORD=password123
      - MONGODB_DATABASE=api
    ports:
      - 27017:27017

  mongo-express:
      image: mongo-express
      restart: always
      ports:
        - 8081:8081
      environment:
        ME_CONFIG_MONGODB_ADMINUSERNAME: root
        ME_CONFIG_MONGODB_ADMINPASSWORD: iamroot
      depends_on:
        - mongo
        - app

Dockerfile文件

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-bionic AS build

WORKDIR /vsdbg
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
            unzip \
    && rm -rf /var/lib/apt/lists/* \
    && curl -sSL https://aka.ms/getvsdbgsh \
        | bash /dev/stdin -v latest -l /vsdbg
        
# Not copying anything since it's being mounted and managed by docker-compose volumes
WORKDIR /app
ENV DOTNET_USE_POLLING_FILE_WATCHER 1
EXPOSE 9999

RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4 \
    && echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.0.list \
    && apt-get update \
    && apt-get install -y iputils-ping mongodb-org-shell

ENTRYPOINT dotnet watch --project /app/API/src/Foo.Api/Foo.Api.csproj run --urls=http://+:9999

I added an xUnit test project to exec in and run in app , but I get the same time out stack trace error seen above.我添加了一个 xUnit 测试项目到exec in 并在app中运行,但我得到了上面看到的相同超时堆栈跟踪错误。

I needed to add the mongodb container to the network, and provide it's discovery alias.我需要将 mongodb 容器添加到网络,并提供它的发现别名。

    networks:
        credentials_network:
            # define an alias for service discovery
            aliases:
                - mongo
            ipv4_address: "169.254.170.4"

Have you try with yaml file version: '3.7' ?您是否尝试过使用 yaml 文件version: '3.7' if still can not please try compose with no network defined.如果仍然不能,请尝试在没有定义网络的情况下撰写。

暂无
暂无

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

相关问题 docker-compose 向上 C# ASP.NET MVC 应用程序容器沿着 ZE4728F444B24839E3F84ADF32 连接到:BA - docker-compose up C# ASP.NET MVC app container along side of a postgresql container Failed to connect to [::1]:5432 Docker-compose 从另一个容器访问 MySQL 容器 - Docker-compose MySQL container access from another container 无法连接到Cassandra Docker Container - Can't connect to Cassandra Docker Container .net核心应用程序无法连接到RabbitMQ(两者都通过docker-compose在docker网络中运行) - .net core app ca't connect to rabbitMQ (both running in a docker network via docker-compose) 无法通过主机名连接到 docker 容器中的 MongoDB - Can't connect to MongoDB in docker container via hostname 在 Docker 容器中运行 .Net 5 API 时无法连接到 Postgres - Can't connect to Postgres when running .Net 5 API in Docker container 无法从带有 ASP.NET Core 的 Docker 容器连接到 SQL Server 容器 - Can't connect from the Docker container with ASP.NET Core to SQL Server container Azure 函数 v3 将调试器附加到本地 docker 容器,以 docker-compose (dotnet) 开始 - Azure functions v3 attach debugger to docker container in local started with docker-compose (dotnet) docker-compose 无法请求外部网络 - docker-compose can't request to outside network Azure 应用服务多容器 - 对内部容器的 http 请求(docker compose) - Azure app service multi container - http request to internal container (docker compose)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM