MongoDB says Authentication failed from a Java app against a Docker container
MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017Short 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.
Fix it fast
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 admin2Match what you see, then jump to its fix
- 1
Authentication 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
mongosh 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
The password has one of $ : / ? # [ ] @ and authentication fails only through the URI, not in mongosh.The password contains characters that break the URIFix - 4
The container starts and accepts connections, but no user exists at all.Only one of the two root variables was setFix
- 1
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 volumes2Fix
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 -d3Verify
Log in with the new credentials from inside the container.
docker exec -it mongo mongosh -u root -p 'your-password' --authenticationDatabase adminConfirmed by github.com
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.yml2Fix
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=admin3Verify
Restart the app and watch for the first query to succeed without error 18.
docker compose logs --tail 50 mongoConfirmed by mongodb.com
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=admin3Verify
Start the app again and confirm the connection opens.
docker compose logs --tail 50 mongoConfirmed by mongodb.com
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_INITDB2Fix
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-password3Verify
A login with the new user succeeds after a fresh start.
docker exec -it mongo mongosh -u root -p 'your-password' --authenticationDatabase adminConfirmed by github.com
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
Servers
A Java container dies at start with 'insufficient memory' or errno=12
os::commit_memory failed; error='Not enough space' (errno=12)
The JVM asked the operating system for more memory than the container is allowed to use.
3 causes, each with a fixServers
The Java SDK finds no AWS credentials on an EC2 instance or in a container on it
InstanceProfileCredentialsProvider()
The SDK walks a fixed list of credential sources and the EC2 instance role is the last one.
3 causes, each with a fixServers
docker build stops at COPY because the file is not in the build context
ERROR: failed to solve: failed to compute cache key:
COPY can only read files that are inside the build context, the folder you pass to docker build.
3 causes, each with a fixServers
Docker build fails to resolve the openjdk slim-buster base image
failed to resolve source metadata for docker.io/library/openjdk:21-slim-buster
The tag you named does not exist any more.
2 causes, each with a fixServers
Grafana says connection refused to Prometheus on localhost:9090
Err reading Prometheus: Post "http://localhost:9090/api/v1/query": dial tcp 127.0.0.1:9090: connect: connection refused
Inside a container, localhost means that container, not your machine or the other container.
3 causes, each with a fixServers
Testcontainers fails with Could not connect to Ryuk at localhost
docker ps shows a testcontainers/ryuk container while the test fails
Ryuk is the helper container Testcontainers starts to clean up after tests.
3 causes, each with a fix