Docker部署PHP网站出现MongoClient PHP类不存在问题求助
Hey there, let's break down why you're hitting this error even though your phpinfo shows the mongodb extension is loaded:
The Core Issue: Two Different MongoDB Extensions
You've installed the official modern mongodb extension (evidenced by docker-php-ext-mongodb.ini), but MongoClient belongs to the old, deprecated mongo extension—they're two completely separate packages.
The modern mongodb extension uses the MongoDB\Client class (with a namespace) instead of the old MongoClient. That's why your code can't find the class, even though the extension is present.
Step-by-Step Fixes
1. Update Your Code to Use the Modern Class
If you control the codebase, replace instances of:
$client = new MongoClient();
With the modern namespace-aware class:
// Option 1: Use the full namespace $client = new MongoDB\Client(); // Option 2: Add a use statement at the top of your file use MongoDB\Client; $client = new Client();
2. Verify the Extension is Properly Loaded
Double-check that the mongodb extension is active:
- Run this command inside your PHP-FPM container:
You should seephp -m | grep mongodbmongodbin the output. - Or look for the "mongodb" section in your phpinfo page—it should detail the extension version and configuration.
3. (Not Recommended) Install the Deprecated mongo Extension (Only for Legacy Apps)
If you're stuck with old code that relies on MongoClient, note that the mongo extension is no longer maintained and doesn't support PHP 7.0+. If your PHP version is <= 5.6, you can add this to your Dockerfile to install it:
RUN pecl install mongo-1.6.16 && docker-php-ext-enable mongo
Again, this is not ideal—upgrading your code to use the modern extension is the safer, long-term fix.
内容的提问来源于stack exchange,提问作者Anthony

