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
asked a year ago106 views
No Answers

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions