写入 dockerized MongoDB 时出错

Error while write into dockerized MongoDB

我在 docker 容器中有 运行 mongo 数据库,命令为:

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]

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

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' my-mongo

问题是我在 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,问题已解决。非常感谢