首页 > 解决方案 > 使用另一个容器连接到 MongoDB docker 容器的问题

问题描述

将 docker 容器连接到另一个容器时出现问题。我可以在容器外部本地连接到它,但从容器内部不起作用。这是堆栈跟踪

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f9cf7b6d9d395e79548d42a, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]>

我的 docker-compose.yml 文件非常简单明了。没有什么独特的

  mongod:
    restart: always
    image: mongo:latest
    volumes:
      - ./mongodb/mongod.conf:/etc/mongod.conf
    ports:
      - "27017:27017"
    command: mongod

  app:
    build: ./app
    container_name: django-gunicorn
    restart: always
    env_file:
      - ./app/django.env
    ports:
      - "8000:8000"
    command:
      "gunicorn --workers=2 --bind=0.0.0.0:8000 webapp.wsgi:application"

我已在 mongod.conf 中将端口绑定到 0.0.0.0。我还缺少什么?

标签: pythondjangomongodbdocker

解决方案


您正在尝试连接localhost,但 mongodb 容器的主机名将是docker-compose.yml文件中给出的服务名称

更新要使用的连接参数

host="mongod",# name of service in compose file

推荐阅读