PyMongo 身份验证失败:{'ok':0.0,'errmsg':'Authentication failed.','code':18,'codeName':'AuthenticationFailed'

PyMongo Auth Failure: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'

奇怪的是,我 运行 SLS Python Lambdas 在 Docker 容器中,MongoDB 实例在单独的容器中。我能够从主机上的公开端口进行身份验证以连接到实例。

但是,无论出于何种原因,SLS 容器内部都不想连接 :S

# mongodb://root:password@mongodb/test_db?retryWrites=true&w=majority
db_uri = "mongodb://" + usr + ":" + pwd + "@" + url + "/test_db?retryWrites=true&w=majority"
client = pymongo.MongoClient(db_uri)

db = client[mongo_db_name]
collection = db[mongo_collection_name]
version: "3.8"
services:
  mongodb:
    image : mongo
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=password
      - MONGO_INITDB_DATABASE=test_db
      - PUID=1000
      - PGID=1000
    ports: 
      - "27000:27017"
    restart: unless-stopped
    volumes:
      - ./mongodb/init.js:/docker-entrypoint.initdb.d/init.js

  python:
    build: python
    depends_on:
      - mongodb
    ports: 
      - "3000:3000"
    restart: unless-stopped
    volumes:
      - ./python:/usr/src/app

需要添加authSource (https://pymongo.readthedocs.io/en/stable/examples/authentication.html#default-database-and-authsource)

db_uri = "mongodb://" + usr + ":" + pwd + "@" + \
    url + "/test_db?authSource=admin&retryWrites=true&w=majority"