我刚刚在AWS Linux实例上安装并配置了MongoDB,并且我很难使用PHP和MongoClient
类远程连接它,尽管对配置进行了严格的检查。
我在后台运行mongod
进程,具有以下配置:
# mongod.conf
logpath=/var/log/mongodb/mongod.log
logappend=true
fork=true
port=27017
dbpath=/srv/mongodb/
pidfilepath=/var/run/mongodb/mongod.pid
# bind_ip=127.0.0.1
bind_ip=0.0.0.0
我的AWS安全组设置如下:
Custom TCP Rule TCP 27017 [IP of php server]/32
然后是我的PHP脚本,如下所示:
##### TESTING & DEBUG #####
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// Display the status of the mongo extension
echo extension_loaded("mongo") ? "loaded\n" : "not loaded\n";
// Create the connection
$mongo = new MongoClient("mongodb://ec2-xx-xx-xx-xx.compute-1.amazonaws.com");
// Select the test database
$db = $mongo->test;
// Select a collection
$c = $db->collection;
// Get the cursor
$cursor = $c->find();
// Dump the contents of the cursor
echo '<pre>'.print_r($cursor,true).'</pre>';
当然,这是PHP返回的错误:
Uncaught exception 'MongoConnectionException' with message 'Failed to connect to: ec2-xx-xxx-xx-xx.compute-1.amazonaws.com:27017: Connection timed out' in test-mongo.php:14 Stack trace: #0 test-mongo.php(14): MongoClient->__construct('mongodb://ec2-x...') #1 {main} thrown in test-mongo.php on line 14
mongod
服务器进程正在运行,由ps -A
验证:
23171 ? 00:00:01 mongod
任何会导致它无法连接的想法?配置中的所有内容对我来说都是正确的。