Node.js container authentication failed when connecting to mongodb container in AWS ECS Fargate (awsvpc network mode)

0

I have created an ecs fargate task and there are two containers(node.js app container and mongodb container) in it. The problem is when I create service from that task definition,Node.js app can't connect to mongodb container with username and password.It said AuthenticationFailed with code:18.The service runs in awsvpc network mode.

I have configure my mongodb container with env variables like this.

MONGO_INITDB_ROOT_USERNAME=mydbuser

MONGO_INITDB_ROOT_PASSWORD=mydbpassword

MONGO_INITDB_DATABASE=my-db

And in node.js app container,

MONGODB_USERNAME = mydbuser

MONGODB_PASSWORD = mydbpassword

MONGODB_URL = localhost

I use localhost for MONGODB_URL because AWS Docs says when you run your fargate task in awsvpc network mode,Containers that belong to the same task can communicate over the localhost interface.

and the connection string in node.js code is like this.

mongoose.connect(`mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@${process.env.MONGODB_URL}:27017/my-db?authSource=admin`,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  },
  (err) => {
    if (err) {
      console.error('FAILED TO CONNECT TO MONGODB');
      console.error(err);
    } else {
      console.log('CONNECTED TO MONGODB!!');
      app.listen(80);
    }
  }
);

But the node.js app container can't connect to mongodb,It always says authentication failed and exit.Please can you help me what I'm missing.

Here is the logs from node.js container.

FAILED TO CONNECT TO MONGODB
mongodb://mydbuser:mydbpassword:27017/my-db?authSource=admin
MongoError: Authentication failed.
    at MessageStream.messageHandler (/app/node_modules/mongodb/lib/cmap/connection.js:299:20)
    at MessageStream.emit (node:events:512:28)
    at processIncomingData (/app/node_modules/mongodb/lib/cmap/message_stream.js:144:12)
    at MessageStream._write (/app/node_modules/mongodb/lib/cmap/message_stream.js:42:5)
    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:766:22)
    at Socket.emit (node:events:512:28)
    at addChunk (node:internal/streams/readable:324:12)
    at readableAddChunk (node:internal/streams/readable:297:9)
    at Readable.push (node:internal/streams/readable:234:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
  ok: 0,
  code: 18,
  codeName: 'AuthenticationFailed'
}
tzs
질문됨 일 년 전117회 조회
답변 없음

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠