Flask-PyMongo连接Docker容器化MongoDB时认证失败问题排查求助
Hey there, let’s work through this authentication error you’re hitting. I’ve looked over your code and Docker setup, and here are the key areas to check and fix:
1. Verify Your MongoDB Initialization
First, let’s make sure your MongoDB user is set up correctly. You’re using an init-db.js script to initialize the database—if this script isn’t creating the user with the right permissions or in the correct authentication database, that’s a common cause of error code 18.
Correct Init Script Example
If you’re using the official MongoDB image’s default root user setup, your init-db.js should look like this (or ensure your db-env-vars.env uses the official variables):
// Connect to the admin database (where root users are stored) db = db.getSiblingDB('admin'); // Create root user with access to your cars_db db.createUser({ user: 'root', pwd: 'pass', roles: [ { role: 'readWrite', db: 'cars_db' }, { role: 'root', db: 'admin' } ] });
Or if you’re relying on the official image’s auto-initialization, your db-env-vars.env must include:
MONGO_INITDB_ROOT_USERNAME=root MONGO_INITDB_ROOT_PASSWORD=pass MONGO_INITDB_DATABASE=cars_db
The official MongoDB image uses these variables to create a root user in the admin database automatically—this is critical because your app needs to authenticate against admin (not cars_db) for this user.
2. Fix Your Flask-PyMongo Connection Config
Your authentication is failing because your app isn’t specifying the correct authentication source. Here’s how to fix both of your config approaches:
Option 1: Use the Explicit Config (Uncommented Version)
Uncomment your original config and add the critical authentication source setting (plus an explicit port for clarity):
app.config['MONGO_HOST'] = os.environ['MONGODB_HOSTNAME'] app.config['MONGO_DBNAME'] = os.environ['MONGODB_DATABASE'] app.config['MONGO_USERNAME'] = os.environ['MONGODB_USERNAME'] app.config['MONGO_PASSWORD'] = os.environ['MONGODB_PASSWORD'] app.config['MONGO_AUTH_SOURCE'] = 'admin' app.config['MONGO_PORT'] = 27017 mongo = PyMongo(app, config_prefix='MONGO')
The MONGO_AUTH_SOURCE = 'admin' line is key—it tells PyMongo to authenticate against the admin database (where your root user is created by default), instead of trying to use cars_db as the auth source (which won’t work for the root user).
Option 2: Fix the MONGO_URI
Add ?authSource=admin to the end of your URI—this tells PyMongo to authenticate against the admin database where your root user lives:
app.config["MONGO_URI"] = ( f'mongodb://{os.environ["MONGODB_USERNAME"]}:' f'{os.environ["MONGODB_PASSWORD"]}@' f'{os.environ["MONGODB_HOSTNAME"]}:27017/' f'{os.environ["MONGODB_DATABASE"]}?authSource=admin' ) mongo = PyMongo(app)
3. Validate Environment Variable Consistency
Double-check that the credentials in your docker-compose.yml match exactly what’s in your MongoDB setup:
- Your app service uses
MONGODB_USERNAME: rootandMONGODB_PASSWORD: pass - Your MongoDB service’s
db-env-vars.envmust have the sameroot/passcredentials (or yourinit-db.jsuses these values)
4. Test Authentication Directly in MongoDB
To rule out database-side issues, log into your MongoDB container and verify the user works:
# Enter the MongoDB container docker exec -it cars_db mongosh -u root -p pass --authenticationDatabase admin # Switch to your cars_db and test write access use cars_db; db.car_tb.insertOne({brand: "Toyota", model: "Camry"});
If this works, the database user is set up correctly—your issue is definitely in the app’s connection config.
5. Clean Up Old Data Volumes (If Needed)
If you’ve restarted your MongoDB container multiple times, old cached user data might be causing conflicts. Wipe the volume and rebuild:
# Stop containers and delete volumes docker-compose down -v # Rebuild and restart docker-compose up --build
Note: This will delete all existing MongoDB data, so back up anything important first.
Final Check
After making these changes, restart your app and test the /cars endpoint. The authentication error should be gone if you’ve addressed the auth source and credential consistency.
内容的提问来源于stack exchange,提问作者Jesus Fernandez

