You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker部署MongoDB认证失败问题求助

MongoDB Docker容器认证失败问题:无法执行show collections及db.auth失败

这是我首次在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:00:01