I’m trying to set up a mongodb instance using docker compose, but I'm running into an authentication issue. here’s my docker-compose.yml
file:
version: '3.9'
services:
mongo:
image: mongo:latest
restart: always
container_name: mongodb
ports:
- '27017:27017'
volumes:
- mongodb:/data/db
environment:
MONGO_INITDB_ROOT_USERNAME: eagle
MONGO_INITDB_ROOT_PASSWORD: 123
MONGO_INITDB_DATABASE: DB
volumes:
mongodb: {}
when I try to connect, I get the following error in the logs:
{"t":{"$date":"2024-10-20T00:16:43.975+00:00"},
"s":"I",
"c":"ACCESS",
"id":5286307,
"ctx":"conn13",
"msg":"Failed to authenticate",
"attr":{
"client":"172.19.0.1:49014",
"isSpeculative":true,
"isClusterMember":false,
"mechanism":"SCRAM-SHA-256",
"user":"eagle",
"db":"DB",
"error":"UserNotFound: Could not find user \"eagle\" for db \"DB\"",
"result":11,
"metrics":{
"conversation_duration":{
"micros":271,
"summary":{
"0":{
"step":1,
"step_total":2,
"duration_micros":245
}
}
},
"extraInfo":{}
}
}
}
{"t":{"$date":"2024-10-20T00:16:43.976+00:00"},
"s":"I",
"c":"ACCESS",
"id":6788604,
"ctx":"conn13",
"msg":"Auth metrics report",
"attr":{
"metric":"acquireUser",
"micros":0
}
}
My user "eagle" could not be found for the database "DB." I’ve double-checked the environment variables, and they seem correct.
This connection string should work: mongodb://eagle:123@localhost:27017/DB
, but in Datagrid I get this error when I try to connect:
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='eagle', source='DB', password= , mechanismProperties= }
Any insights on how to resolve it would be appreciated!
MONGO_INITDB_DATABASE specifies the context for the init scripts, it has nothing to do with the root user.
MONGO_INITDB_ROOT_USERNAME is created in admin
database.
As @ray alluded, you have to specify auth database in the command line options. mongosh syntax is --authenticationDatabase=admin
so the whole command would be
mongosh -u eagle -p 123 --authenticationDatabase=admin mongodb://localhost:27017/DB
or you can rely on defaults:
mongosh -u eagle -p 123
The last command will log you into test database, so you will need to use DB
to switch to DB database.