[Fixed] error: MongoError: Authentication failed. I am using docker and mongoose

Issue

I try to connect to mongoDB through docker-compose but i get the same error over and over again although i tried all the solutions from the net. Thank you.

I have my docker-compose.yml as

# Use root/example as user/password credentials
version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    container_name: mongo
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
      MONGO_INITDB_DATABASE: test
      MONGO_USERNAME: admin
      MONGO_PASSWORD: example
      
    volumes:
      - ./data:/data/db
      - ./mongo-entrypoint.sh:/docker-entrypoint-initdb.d/mongo-init.sh:ro
    command: mongod


  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example

And I have such a shell script

mongo -- "$MONGO_INITDB_DATABASE" <<EOF
  db.createUser({
    user: "$MONGO_USERNAME",
    pwd: "$MONGO_PASSWORD",
    roles: [
      { role: 'readWrite', db: "$MONGO_INITDB_DATABASE" }
    ]
  })
EOF

And I try to connect to database by:

mongoose
  .connect("mongodb://admin:[email protected]:27017/test")
  .then(() => console.log("connected"))
  .catch((e) => console.log("error:", e));

In Linux my friend can connect with the same code pieces but I am getting this error :

running on 3000
error: MongoError: Authentication failed.
    at MessageStream.messageHandler (C:\Users\kamad\Desktop\3-2\cs308\proje\backend\node_modules\mongodb\lib\cmap\connection.js:268:20)
    at MessageStream.emit (events.js:315:20)
    at processIncomingData (C:\Users\kamad\Desktop\3-2\cs308\proje\backend\node_modules\mongodb\lib\cmap\message_stream.js:144:12)
    at MessageStream._write (C:\Users\kamad\Desktop\3-2\cs308\proje\backend\node_modules\mongodb\lib\cmap\message_stream.js:42:5)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at MessageStream.Writable.write (internal/streams/writable.js:303:10)
    at Socket.ondata (internal/streams/readable.js:719:22)
    at Socket.emit (events.js:315:20)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
    at Socket.Readable.push (internal/streams/readable.js:223:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {
  ok: 0,
  code: 18,
  codeName: 'AuthenticationFailed'
}

Solution

I solved this just by changing the port from 27017 to 27018. Unfortunately, another app of mine was using that port.

Leave a Reply

(*) Required, Your email will not be published