首页 > 解决方案 > MongoDB + PHP:错误“无法连接到 127.0.0.1:27017”

问题描述

我已经使用 MongoDB 和一些 .php 文件运行了一个 EC2 实例来部署一个小网页。PHP 展示了取自 MongoDB 的产品。

<?php
include_once("header.php");
require 'vendor/autoload.php';
$uri="mongodb://localhost";
$client=new MongoDB\Client($uri);

$collection = $client->tienda->categorias->find();
$categorias=array();

当我创建数据库时,这没问题。重新登录 EC2 网页后,DB 中没有显示任何内容。当我尝试检查数据库时,此错误返回:

> use tienda
> show collections
2020-05-13T17:29:29.612+0000 I NETWORK  [thread1] trying reconnect to 127.0.0.1:27017 (127.0.0.1) failed
2020-05-13T17:29:29.612+0000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2020-05-13T17:29:29.612+0000 I NETWORK  [thread1] reconnect 127.0.0.1:27017 (127.0.0.1) failed failed
2020-05-13T17:29:29.612+0000 E QUERY    [thread1] Error: socket exception [CONNECT_ERROR] for couldn't connect to server 127.0.0.1:27017, connection attempt failed :
runClientFunctionWithRetries@src/mongo/shell/session.js:346:31
runCommand@src/mongo/shell/session.js:412:25
DB.prototype._runCommandImpl@src/mongo/shell/db.js:145:16
DB.prototype.runCommand@src/mongo/shell/db.js:161:20
DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:930:19
DB.prototype.getCollectionInfos@src/mongo/shell/db.js:953:19
DB.prototype.getCollectionNames@src/mongo/shell/db.js:964:16
shellHelper.show@src/mongo/shell/utils.js:809:9
shellHelper@src/mongo/shell/utils.js:706:15
@(shellhelp2):1:1
2020-05-13T17:24:05.117+0000 I NETWORK  [thread1] trying reconnect to 127.0.0.1:27017 (127.0.0.1) failed
2020-05-13T17:24:05.117+0000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2020-05-13T17:24:05.117+0000 I NETWORK  [thread1] reconnect 127.0.0.1:27017 (127.0.0.1) failed failed

经过一些谷歌小时后,我发现保持数据库工作的唯一方法是在新标签上运行

$ mongod

关闭此选项卡后,DB 停止工作,webpay 停止显示产品。有没有什么办法解决这一问题?顺便说一句,我是 MongoDB 的新手。

标签: phpdatabasemongodbamazon-ec2

解决方案


您可以将 MongoDB 进程作为守护进程运行

mongod --fork --logpath /var/log/mongodb/mongod.log

logpath 是保存日志的位置。

文档: https ://docs.mongodb.com/manual/tutorial/manage-mongodb-processes/


推荐阅读