skip to Main Content

I created a mongodb instance in a docker container and I am struggling to get a connection to change anything in the database. Does anyone have a hint, what might be wrong?

Here is the docker run command:

# Start the docker container
echo "mongodb password in file" $(pwd)/mongodb.pass
docker run 
    -p 27017:27017 
    --restart unless-stopped 
    --name mongodb 
    -v airlist:/data/db 
    -v $(pwd)/mongodb.pass:/mongodb.pass 
    -d 
    --network airfetch 
    -e MONGO_INITDB_ROOT_USERNAME=airfetch 
    -e MONGO_INITDB_ROOT_PASSWORD=airlist27101978 
    mongo:latest 

Using this docker container, I want to access the database.
I run this python script on the host of the docker container. Since the port is exposed, this should work. Indeed, when I just pass auth_string=mongodb://localhost:27017, I get a response from the server_info method, but cannot insert any records or databases.

import pymongo
import urllib.parse

username = urllib.parse.quote_plus('airfetch')
password = urllib.parse.quote_plus('airlist27101978')
auth_db = 'admin'
auth_source='?authSource=admin&retryWrites=true&w=majority'
auth_string = f"mongodb://{username}:{password}@localhost:27017/{auth_db}{auth_source}"
myclient = pymongo.MongoClient(auth_string)

However, I get the error message:

pymongo.errors.OperationFailure: Authentication failed., full error: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}  

2

Answers


  1. Chosen as BEST ANSWER

    I found the problem: I did not delete the volume after I changed the password. Apparently, the credentials are stored in data/db within the container.


  2. You need to add authsource:

    ?authSource=admin&retryWrites=true&w=majority :

    From:

    auth_string = f"mongodb://{username}:{password}@localhost:27017/{auth_db}"
    

    To:

    auth_string = f"mongodb://{username}:{password}@localhost:27017/{auth_db}?authSource=admin&retryWrites=true&w=majority"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search