I deployed MongoDB using docker-compose. In docker-compose.yml
I set user authentication
cis_mongodb:
container_name: cis_mongodb
image: mongo
environment:
MONGO_INITDB_ROOT_USERNAME: ${MONGO_USER}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD}
In project root there is a file .env
with variables MONGO_USER
and MONGO_PASSWORD
.
I use following code to connect to MongoDB database
import pymongo
dbclient = pymongo.MongoClient(
f'mongodb://{username}:{password}@{mongo_ip}:{mongo_port}/test',
)
WHen I run this code there is an error
pymongo.errors.OperationFailure: Authentication failed., full error: {'ok': 0.0, 'errsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}
username
and password
are correct.
I also tried following urls:
f'mongodb://{username}:{password}@{mongo_ip}:{mongo_port}/test'
f'mongodb://{username}:{password}@{mongo_ip}:{mongo_port}/test?authSource=admin'
and this way (tip from here):
import urllib.parse
username = urllib.parse.quote_plus('login')
password = urllib.parse.quote_plus('password')
What can be the cause of the problem?
PS: version of MongoDB is 6.0.8