Skip to content
Latchkey

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.

Terminal
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.

.github/workflows/ci.yml
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=admin

Recreate the volume if credentials changed

The root user is created only on first init. Drop the volume so it is recreated with new credentials.

Terminal
docker compose down -v && docker compose up -d mongo

How to prevent it

  • Include authSource=admin when 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.

Frequently asked questions

What causes "MongoDB "Authentication failed""?
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.
How do I fix MongoDB "Authentication failed"?
Use the same root credentials and authenticate against admin.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card