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

使用Nginx时mongo-express访问MongoDB认证失败排查求助

解决mongo-express连接MongoDB的认证问题

问题现象

使用mongo-express容器访问MongoDB时触发认证错误:

Command listDatabases requires authentication

8081端口页面为空,容器日志报错如下:

No custom config.js found, loading config.default.js
Welcome to mongo-express
------------------------
/node_modules/mongodb/lib/cmap/connection.js:231
callback(new error_1.MongoServerError(document));


MongoServerError: Command listDatabases requires authentication
    at Connection.onMessage (/node_modules/mongodb/lib/cmap/connection.js:231:30)
    at MessageStream.<anonymous> (/node_modules/mongodb/lib/cmap/connection.js:61:60)
    at MessageStream.emit (node:events:517:28)
    at processIncomingData (/node_modules/mongodb/lib/cmap/message_stream.js:125:16)
    at MessageStream._write (/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
    at writeOrBuffer (node:internal/streams/writable:392:12)
    at _write (node:internal/streams/writable:333:10)
    at Writable.write (node:internal/streams/writable:337:10)
    at Socket.ondata (node:internal/streams/readable:809:22)
    at Socket.emit (node:events:517:28) {
  ok: 0,
  code: 13,
  codeName: 'Unauthorized',
  [Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.19.0

根因定位

  1. 环境变量名错误:mongo-express的MongoDB管理员认证环境变量前缀应为ME_CONFIG_MONGODB_,而非配置中写的MONGO_CONFIG_MONGODB_,导致认证信息未被正确读取。
  2. 潜在数据卷遗留问题:如果之前未启用认证就启动过MongoDB容器,mongodb-data卷中可能残留未开启认证的数据库配置,导致新的认证设置不生效。

解决方案

步骤1:修正mongo-express的环境变量配置

修改local.yml中mongo-express服务的环境变量,替换错误的变量名前缀:

mongo-express:
  image: mongo-express
  depends_on:
    - mongodb
  ports:
    - "8081:8081"
  environment:
    ME_CONFIG_MONGODB_ADMINUSERNAME: ${MONGO_ROOT_USERNAME}
    ME_CONFIG_MONGODB_ADMINPASSWORD: ${MONGO_ROOT_PASSWORD}
    ME_CONFIG_MONGODB_SERVER: mongodb
    ME_CONFIG_BASICAUTH_USERNAME: admin
    ME_CONFIG_BASICAUTH_PASSWORD: admin123
  networks:
    - invoice

步骤2:清理MongoDB数据卷(可选,步骤1无效时执行)

若之前MongoDB容器未开启认证就运行过,需清理遗留数据卷:

# 停止并删除相关容器
docker-compose -f local.yml down
# 删除MongoDB数据卷(替换为你的实际项目名称)
docker volume rm your-project-name_mongodb-data
# 重新启动容器
docker-compose -f local.yml up -d

可通过docker volume ls查看你的数据卷全称

步骤3:重启容器

执行命令强制重建并重启相关服务:

docker-compose -f local.yml up -d --force-recreate mongo-express mongodb

验证

访问http://localhost:8081,输入mongo-express基础认证用户名admin和密码admin123,即可正常查看MongoDB数据库列表。

内容的提问来源于stack exchange,提问作者Shubham kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 00:51:20