【问题标题】:Can't authenticate with mongoDB from docker-compose service无法从 docker-compose 服务向 mongoDB 进行身份验证
【发布时间】:2023-03-05 06:54:01
【问题描述】:

我想要做什么

我正在尝试设置一个 docker-compose 定义,其中我有一个 mongoDB 容器和一个连接到它的 nodeJS 容器。

version: "3.9"

services:

  events-db:
    image: mongo
    volumes:
      - db-volume:/data/db
    environment:
      MONGO_INITDB_ROOT_USERNAME: $SANDBOX_DB_USER
      MONGO_INITDB_ROOT_PASSWORD: $SANDBOX_DB_PASS
      MONGO_INITDB_DATABASE: sandboxdb

  app:
    image: node:15.12.0
    user: node
    working_dir: /home/node/app
    volumes:
      - ./:/home/node/app:ro
    environment:
      MDB_CONNECTION: mongodb://$SANDBOX_DB_USER:$SANDBOX_DB_PASS@events-db:27017/sandboxdb
    command: node myapp
    depends_on:
      - events-db

volumes:
  db-volume:

连同声明凭据的.env 文件(计划在我将其部署到生产环境时使用适当的环境变量):

SANDBOX_DB_USER=myuser
SANDBOX_DB_PASS=myp4ss

最后,我的 nodejs 脚本 myapp.js 只是尝试连接、获取对集合的引用并插入文档:

require('dotenv').config()
const { MongoClient } = require('mongodb')

async function main () {
  console.log('Connecting')
  const client = new MongoClient(process.env.MDB_CONNECTION, {
    connectTimeoutMS: 10000,
    useUnifiedTopology: true,
  })
  await client.connect()
  const db = client.db()
  const events = db.collection('events')

  console.log('Inserting an event')
  await events.insertOne({
    type: 'foo',
    timestamp: new Date(),
  })

  console.log('Done.')
  process.exit(0)
}

if (require.main === module) {
  main()
}

结果

当我运行docker-compose config 时,我看到以下输出,所以我希望它能够工作:

$ docker-compose config
services:
  app:
    command: node myapp
    depends_on:
      events-db:
        condition: service_started
    environment:
      MDB_CONNECTION: mongodb://myuser:myp4ss@events-db:27017/sandboxdb
    image: node:15.12.0
    user: node
    volumes:
    - C:\workspace\dcsandbox:/home/node/app:ro
    working_dir: /home/node/app
  events-db:
    environment:
      MONGO_INITDB_DATABASE: sandboxdb
      MONGO_INITDB_ROOT_PASSWORD: myp4ss
      MONGO_INITDB_ROOT_USERNAME: myuser
    image: mongo
    volumes:
    - db-volume:/data/db:rw
version: '3.9'
volumes:
  db-volume: {}

但是,当我运行docker-compose up 时,我看到我的节点容器无法连接到 mongoDB 以插入事件:

events-db_1  | {"t":{"$date":"2021-04-07T13:57:36.793+00:00"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}
app_1        | Connecting
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.811+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.27.0.3:34164","connectionId":1,"connectionCount":1}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.816+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn1","msg":"client metadata","attr":{"remote":"172.27.0.3:34164","client":"conn1","doc":{"driver":{"name":"nodejs","version":"3.6.6"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"4.19.128-microsoft-standard"},"platform":"'Node.js v15.12.0, LE (unified)"}}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.820+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.27.0.3:34166","connectionId":2,"connectionCount":2}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.822+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn2","msg":"client metadata","attr":{"remote":"172.27.0.3:34166","client":"conn2","doc":{"driver":{"name":"nodejs","version":"3.6.6"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"4.19.128-microsoft-standard"},"platform":"'Node.js v15.12.0, LE (unified)"}}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.822+00:00"},"s":"I",  "c":"ACCESS",   "id":20251,   "ctx":"conn2","msg":"Supported SASL mechanisms requested for unknown user","attr":{"user":"myuser@sandboxdb"}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.823+00:00"},"s":"I",  "c":"ACCESS",   "id":20249,   "ctx":"conn2","msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-256","principalName":"myuser","authenticationDatabase":"sandboxdb","client":"172.27.0.3:34166","result":"UserNotFound: Could not find user \"myuser\" for db \"sandboxdb\""}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.824+00:00"},"s":"I",  "c":"ACCESS",   "id":20249,   "ctx":"conn2","msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-1","principalName":"myuser","authenticationDatabase":"sandboxdb","client":"172.27.0.3:34166","result":"UserNotFound: Could not find user \"myuser\" for db \"sandboxdb\""}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.826+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn1","msg":"Connection ended","attr":{"remote":"172.27.0.3:34164","connectionId":1,"connectionCount":1}}
app_1        | /home/node/app/node_modules/mongodb/lib/cmap/connection.js:268
app_1        |           callback(new MongoError(document));
app_1        |                    ^
app_1        |
app_1        | MongoError: Authentication failed.
app_1        |     at MessageStream.messageHandler (/home/node/app/node_modules/mongodb/lib/cmap/connection.js:268:20)
app_1        |     at MessageStream.emit (node:events:369:20)
app_1        |     at processIncomingData (/home/node/app/node_modules/mongodb/lib/cmap/message_stream.js:144:12)
app_1        |     at MessageStream._write (/home/node/app/node_modules/mongodb/lib/cmap/message_stream.js:42:5)
app_1        |     at writeOrBuffer (node:internal/streams/writable:395:12)
app_1        |     at MessageStream.Writable.write (node:internal/streams/writable:340:10)
app_1        |     at Socket.ondata (node:internal/streams/readable:750:22)
app_1        |     at Socket.emit (node:events:369:20)
app_1        |     at addChunk (node:internal/streams/readable:313:12)
app_1        |     at readableAddChunk (node:internal/streams/readable:288:9) {
app_1        |   ok: 0,
app_1        |   code: 18,
app_1        |   codeName: 'AuthenticationFailed'
app_1        | }
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.832+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn2","msg":"Connection ended","attr":{"remote":"172.27.0.3:34166","connectionId":2,"connectionCount":0}}
dcsandbox_app_1 exited with code 1

我已将完整输出放在https://pastebin.com/uNyJ6tiy 以及此 repo 中的示例代码:https://github.com/akatechis/example-docker-compose-mongo-node-auth

【问题讨论】:

  • 尝试写入控制台连接字符串
  • 当我在节点脚本中记录 process.env.MDB_CONNECTION 时,我看到 docker-compose 的以下输出:app_1 | Connecting to mongodb://myuser:myp4ss@events-db:27017/sandboxdb

标签: node.js mongodb docker authentication docker-compose


【解决方案1】:

经过更多的挖掘,我设法弄清楚了。问题是MONGO_INITDB_ROOT_USERNAMEMONGO_INITDB_ROOT_PASSWORD 变量只是设置了root 用户的凭据,而MONGO_INITDB_DATABASE 只是设置了/docker-entrypoint-initdb.d 中脚本的初始数据库。

默认情况下,root 用户被添加到 admin 数据库中,因此通过删除连接字符串的 /sandboxdb 部分,我能够让我的节点应用程序以 root 用户身份针对 admin DB 进行身份验证.

虽然这并没有完全完成我最初想要的(为我的数据库创建一个单独的非 root 用户,并使用它进行身份验证),但我认为这让我处于正确的位置使用初始化脚本设置我想要拥有的用户帐户的路径。

【讨论】:

    猜你喜欢
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多