MongoDB "Authentication failed" (bad auth) in CI
MongoDB reached the auth step and rejected the credentials with "Authentication failed" (code 18). The connection works; the username, password, or authSource does not match the user the container created.
What this error means
The driver fails with "MongoServerError: Authentication failed" or "bad auth : authentication failed", while a no-auth connection to the same host succeeds.
MongoServerError: Authentication failed.
{ ok: 0, code: 18, codeName: 'AuthenticationFailed' }Common causes
The credentials do not match the root user env
The image creates the root user from MONGO_INITDB_ROOT_USERNAME/MONGO_INITDB_ROOT_PASSWORD only on a fresh data dir. A different user/password in the URI is rejected.
The authSource is wrong
The root user lives in the admin database. A URI that authenticates against the app database without authSource=admin fails.
How to fix it
Match credentials and set authSource
Use the same root credentials and authenticate against admin.
services:
mongo:
image: mongo:7
env:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: root_pw
ports: ['27017:27017']
env:
MONGODB_URI: mongodb://root:root_pw@127.0.0.1:27017/app_test?authSource=adminRecreate the volume if credentials changed
The root user is created only on first init. Drop the volume so it is recreated with new credentials.
docker compose down -v && docker compose up -d mongoHow to prevent it
- Include
authSource=adminwhen using the root user. - Keep the root credentials and the URI in sync from one source.
- Do not reuse the data volume across credential changes.