Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Servers, nginx and Docker

MongoDB says Authentication failed from a Java app against a Docker container

ErrorMongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017

Short answer

Error 18 means MongoDB found no matching user in the database it checked. With the Docker image, the usual reasons are: the root user variables were ignored because the data volume already existed, the connection string lacks authSource=admin, the password has unencoded characters, or only one of the two variables was set.

  • Applies to MongoDB 8.0 Docker image, Docker Compose v2, Spring Boot 3, Java 21
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Try the same user and password from inside the container, naming the admin database as the place the user lives. If this works, the container is fine and the problem is in the app's connection string.

    docker exec -it mongo mongosh -u root -p 'your-password' --authenticationDatabase admin
  2. 2Match what you see, then jump to its fix

    1. 1Authentication fails right after you changed MONGO_INITDB_ROOT_USERNAME or MONGO_INITDB_ROOT_PASSWORD in the compose file.The root user variables were ignored because the data volume already existedFix
    2. 2mongosh works with --authenticationDatabase admin, but the app fails with the same user.The connection string does not name the admin database as the authentication databaseFix
    3. 3The password has one of $ : / ? # [ ] @ and authentication fails only through the URI, not in mongosh.The password contains characters that break the URIFix
    4. 4The container starts and accepts connections, but no user exists at all.Only one of the two root variables was setFix

What does the error look like?

  • MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017

Cause 1 of 4

The root user variables were ignored because the data volume already existed

1Check

The image creates the root user only when the container starts for the first time on an empty data directory. A pre-existing database is left untouched. List the volumes and see whether the one mounted at /data/db was created before your change.

docker volume ls
docker compose config | grep -A3 volumes

2Fix

Either log in with the credentials the volume was first created with, or, if the data is disposable, remove the volume so the next start runs the init step again. Removing the volume deletes the database.

docker compose down -v
docker compose up -d

3Verify

Log in with the new credentials from inside the container.

docker exec -it mongo mongosh -u root -p 'your-password' --authenticationDatabase admin

Confirmed by github.com

Did this fix it?

Cause 2 of 4

The connection string does not name the admin database as the authentication database

1Check

The root user is created in the admin database. If your URI ends in /yourdb and has no authSource, the driver authenticates against yourdb, where that user does not exist. Only when neither authSource nor a default database is given does the driver use admin.

grep -R "mongodb://" src/main/resources/ docker-compose.yml

2Fix

Add authSource=admin to the URI, or create an application user inside your own database and use that one.

mongodb://root:your-password@localhost:27017/yourdb?authSource=admin

3Verify

Restart the app and watch for the first query to succeed without error 18.

docker compose logs --tail 50 mongo

Confirmed by mongodb.com

Did this fix it?

Cause 3 of 4

The password contains characters that break the URI

1Check

MongoDB requires these characters in a username or password to be percent-encoded in a connection string.

echo "$MONGO_PASSWORD" | grep -E '[$:/?#@]|\[|\]'

2Fix

Percent-encode the password in the URI (for example @ becomes %40), or pick a password without those characters.

# D1fficultP@ssw0rd
mongodb://root:D1fficultP%40ssw0rd@localhost:27017/yourdb?authSource=admin

3Verify

Start the app again and confirm the connection opens.

docker compose logs --tail 50 mongo

Confirmed by mongodb.com

Did this fix it?

Cause 4 of 4

Only one of the two root variables was set

1Check

The image needs both variables to create a user; with only one, no user is created. Look at what the container was given.

docker inspect mongo --format '{{range .Config.Env}}{{println .}}{{end}}' | grep MONGO_INITDB

2Fix

Set both MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD, then recreate the data volume as in the first cause so the init step runs.

services:
  mongo:
    image: mongo:8
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: your-password

3Verify

A login with the new user succeeds after a fresh start.

docker exec -it mongo mongosh -u root -p 'your-password' --authenticationDatabase admin

Confirmed by github.com

Did this fix it?

How do I stop it coming back?

  • Keep the username, password and authSource in one place (an env file) that both the compose file and the app read.
  • Percent-encode any password you put into a URI, or generate passwords that avoid reserved characters.
  • Create a separate application user for your own database instead of using the root user in the app.
  • Know which named volume holds the data, so a credential change is never mistaken for a fresh start.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.