MongoDB "MongoServerError: Authentication failed" in CI
MongoDB accepted the connection and rejected authentication. The username/password is wrong, or the client authenticated against the wrong authSource database. The server is reachable - this is deterministic and will not pass on retry.
What this error means
A driver call fails with "MongoServerError: Authentication failed" (error code 18). It fails the same way every run because the credentials or authSource are wrong.
MongoServerError: Authentication failed.
code: 18,
codeName: 'AuthenticationFailed'Common causes
Wrong username/password
The credentials in the connection string differ from MONGO_INITDB_ROOT_USERNAME/MONGO_INITDB_ROOT_PASSWORD on the service.
Wrong authSource
Root users authenticate against admin. Omitting ?authSource=admin (or pointing it at the app database) makes auth fail.
How to fix it
Set credentials and authSource
Match the connection string to the service credentials and the correct auth database.
services:
mongo:
image: mongo:7
env:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: ${{ secrets.MONGO_PASSWORD }}
env:
MONGO_URL: mongodb://root:${{ secrets.MONGO_PASSWORD }}@127.0.0.1:27017/app?authSource=adminVerify the secret and auth database
- Confirm the password secret is non-empty and the name matches.
- Use
authSource=adminfor the root user created by the image. - Create an app-scoped user if you prefer to authenticate against the app database.
How to prevent it
- Keep Mongo credentials in one secret used by the service and the URL.
- Always set the correct
authSource. - Retrying will not fix an authentication failure - it is deterministic; fix credentials/authSource.