Docker部署MongoDB认证失败问题求助
这是我首次在Stack Overflow提问,英语非母语,若表述有误请谅解。我正在用Go语言开发REST API,使用MongoDB的Docker镜像作为数据库,我的docker-compose.yaml配置如下:
version: '3' services: db: image: mongo container_name: mongo restart: always ports: - '27017:27017' environment: MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME} MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD} volumes: - ./data/db:/data/db api: build : . container_name: restapi restart: always ports: - '8080:8080' environment: MONGO_URI: mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@localhost:27017/?authSource=admin depends_on: - db
我通过.env文件配置了环境变量,执行docker compose up -d --build命令后成功创建mongo和restapi两个容器。但当我执行docker exec -it mongo mongosh进入数据库,执行use admin后再运行show collections时,出现如下错误:
"MongoServerError: not authorized on admin to execute command {
listCollections: 1, filter: {}, cursor: {}, nameOnly: true,
authorizedCollections: false, lsid: { id:
UUID("d02d6b74-0f09-4cee-8c08-b2842b1dc6b2") }, $db: "admin",
$readPreference: { mode: "primaryPreferred" } }"
之后我尝试执行use admin和db.auth('myusername','mypassword'),即便用户名和密码正确,仍提示:MongoServerError: Authentication failed。我已尝试多种方法仍无法解决,恳请各位提供帮助。
内容的提问来源于stack exchange,提问作者Mert Caner EREN

