0

我已经使用命令在 docker 容器中运行了 mongo db:

docker run -d -p 127.0.0.1:27017:27017 --name my-mongo -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=pass mongo:4.4.0

它似乎运作良好。我尝试连接到这个 Mongo 并使用 python 库编写一些文章(我尝试使用同步和异步库)。下面是电机库的代码示例:

import asyncio
import motor.motor_asyncio


def initialization():
    obj_client = motor.motor_asyncio.AsyncIOMotorClient(
        host="127.0.0.1",
        password="pass",
        port=27017,
        username="root"
    )
    obj_database = obj_client["test"]
    obj_collection = obj_database["collection"]
    return obj_database, obj_collection


async def do_insert(db, collection):
    document = {'key': 'value'}
    result = await collection.insert_one(document)
    print('result %s' % repr(result.inserted_id))

if __name__ == "__main__":
    obj_client, obj_database, obj_collection = initialization()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_insert(obj_client, obj_database, obj_collection))

调用 insert_one() 时出现错误:

Traceback (most recent call last):
  File "/Users/user1/Documents/python_projects/unsorted/mongo_inersection.py", line 25, in <module>
    loop.run_until_complete(do_insert(obj_client, obj_database, obj_collection))
  File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/Users/user1/Documents/python_projects/unsorted/mongo_inersection.py", line 19, in do_insert
    result = await collection.insert_one(document)
  File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.8/site-packages/pymongo/collection.py", line 698, in insert_one
    self._insert(document,
  File "/usr/local/lib/python3.8/site-packages/pymongo/collection.py", line 613, in _insert
    return self._insert_one(
  File "/usr/local/lib/python3.8/site-packages/pymongo/collection.py", line 602, in _insert_one
    self.__database.client._retryable_write(
  File "/usr/local/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1497, in _retryable_write
    with self._tmp_session(session) as s:
  File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 113, in __enter__
    return next(self.gen)
  File "/usr/local/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1829, in _tmp_session
    s = self._ensure_session(session)
  File "/usr/local/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1816, in _ensure_session
    return self.__start_session(True, causal_consistency=False)
  File "/usr/local/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1766, in __start_session
    server_session = self._get_server_session()
  File "/usr/local/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1802, in _get_server_session
    return self._topology.get_server_session()
  File "/usr/local/lib/python3.8/site-packages/pymongo/topology.py", line 485, in get_server_session
    self._select_servers_loop(
  File "/usr/local/lib/python3.8/site-packages/pymongo/topology.py", line 215, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:27017: [Errno 61] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f67d9e04b411f070c264a7d, topology_type: Single, servers: [<ServerDescription ('127.0.0.1', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('127.0.0.1:27017: [Errno 61] Connection refused')>]>
[Finished in 31.0s with exit code 1]
[cmd: ['/usr/local/bin/python3', '-u', '/Users/user1/Documents/python_projects/unsorted/mongo_inersection.py']]
[dir: /Users/user1/Documents/python_projects/unsorted]
[path: /usr/bin:/bin:/usr/sbin:/sbin]
4

2 回答 2

1

您可以检查运行 MongoDB 的 docker 容器的 IP 是否是您用来连接 MongoDB 的那个(主机):

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' my-mongo
于 2020-09-21T02:00:22.740 回答
0

问题是我在 docker-machine 的 MacOS 上使用 docker(我忘了):

$ docker-machine ls
NAME      ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER     ERRORS
default   *        virtualbox   Running   tcp://192.168.99.100:2376           v19.03.5 

我使用 192.168.99.100:27017 连接到 MongoDB 并解决了问题。非常感谢

于 2020-09-21T14:45:47.627 回答