myge32
myge32

Reputation: 75

MongoDB + PHP: Error "Failed to connect to 127.0.0.1:27017"

I have running a EC2 instance with MongoDB and some .php files to deploy a little webpage. PHP shows productos taken from 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();

When I created DB it was no problem. After a new login to EC2 webpage doesn't show anything from DB. When I try to check DB this error returns:

> 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

After some google hours the only way I found to keep DB working is running on a new tab

$ mongod

Once I close this tab, DB stops to work and webpay stops to display products. Is there any way to fix this? I'm new to MongoDB btw.

Upvotes: 0

Views: 171

Answers (1)

Farhad
Farhad

Reputation: 752

You can run the MongoDB process as a daemon

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

Where logpath is where logs will be saved.

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

Upvotes: 1

Related Questions