Solved. Q&A: MongoDB MongoNetworkError: failed to connect to server. server is remote server - node.js

mongoose connect to MongoDB fails. But mongo command line can connect to MongoDB.
Code:
var mongoose = require('mongoose');
mongoose.connect('mongodb://192.168.92.131/test', {useNewUrlParser: true});
Result:
(node:6559) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [192.168.92.131:27017] on first connect [Error:
connect EHOSTDOWN 192.168.92.131:27017 - Local (192.168.92.1:60222)
at internalConnect (net.js:835:16)
at defaultTriggerAsyncIdScope (internal/async_hooks.js:301:12)
at net.js:926:9
at processTicksAndRejections
(internal/process/task_queues.js:75:11) {
name: 'MongoNetworkError', errorLabels: [Array],
[Symbol(mongoErrorContextSymbol)]: {}
My MongoDB is installed in a virtual machine running Ubuntu OS. I searched for a solution, but I failed to find a clean solution.
I found a feasible solution to share:
Troubleshooting process
Run mongo command line. Connection ok.
MongoDB does not have access control (user/password) by default. So my code is ok.
IP problem? Mongodb did not start on 192.168.92.131
Google: start mongodb using external ip
Found a solution: https://www.shellhacks.com/mongodb-allow-remote-access/
ether#ubuntu_ether:~$ sudo nano /etc/mongod.conf
No external IP address. So add ip address in mongod.conf
…....
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1, 192.168.92.131
ether#ubuntu_ether:~$ sudo service mongod restart
Run again:
var mongoose = require('mongoose');
mongoose.connect('mongodb://192.168.92.131/test', {useNewUrlParser: true});
OK!!!

Related

Access database on Server with localhost node Project

I have bought a VPS for my website. I have built a small project with vue and node.
In this I used postgresql that is working fine on localhost.
I want to change my database from localhost to the server database where I have installed postgres and made a database and table.
My db.js file looks like this:
const Pool = require('pg').Pool;
const pool = new Pool({
user: "postgres",
password: "root",
database: "todo_database",
host:"45.111.241.15",
port: 5432
});
module.exports = pool;
Then I tried to send form data from the localhost vue page and it gave the following error:
error connecting db Error: connect ECONNREFUSED 45.111.241.15:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '45.111.241.15',
port: 5432
I do not have much knowledge about this and how to solve this.
Can you please guide me what should I do to connect with my server db?
I follow these steps and it worked:
edit your /etc/postgresql/9.1/main/postgresql.conf and change
Connection Settings -
listen_addresses = '*' # what IP address(es) to listen on;
In /etc/postgresql/10/main/pg_hba.conf
IPv4 local connections:
host all all 0.0.0.0/0 md5
Now restart your DBMS
sudo service postgresql restart
Now you can connect with
psql -h hostname(IP) -p 5432 -U postgres

I can't connect to mongo db in ubuntu

MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
2018-10-01T17:38:22.425+0000 W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2018-10-01T17:38:22.426+0000 E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect#src/mongo/shell/mongo.js:251:13
#(connect):1:6
exception: connect failed
I get an error when I try to run mongo on the terminal.
I tried to reinstall and removed lock file and restarted it, but It still doesn't work. I am using AWS, is it some problem about inbound, outbound of network setting in AWS, Or any other problem?
Like the comments above, if you are trying to connect to a mongodb instance on the same host, using 127.0.0.1 it is a mongodb configuration problem, so, that is not possible to be any AWS Security Rules.
So, considering it is a mongodb problem, first try to repair it inside the host with:
sudo rm /var/lib/mongodb/mongod.lock
sudo mongod --repair
sudo service mongodb restart
sudo service mongod status
Refer: https://stackoverflow.com/a/29083477/8407784
After resolved the mongodb config problem, you need to test your connection from another host, setting /etc/mongod.conf - bind_ip = 0.0.0.0 (that means all interfaces), only for testing
Then you need to set your AWS Security Rules on the host instance allowing the external instance to access it on port 27017.

Cant connect to docker mongodb

I am have not used both docker and node a lot so I hope its a simple mistake. I am using docker compose. If I through a browser access,
http://localhost:27017/ I get an:
It looks like you are trying to access MongoDB over HTTP on the native
driver port.
Also logs suggest my mongodb is healty. Last line from when I tried to access through my browser I guess.
2017-01-25T21:11:13.509+0000 I JOURNAL [initandlisten] journal
dir=/data/db/journal 2017-01-25T21:11:13.509+0000 I JOURNAL
[initandlisten] recover : no journal files present, no recovery needed
2017-01-25T21:11:13.546+0000 I JOURNAL [durability] Durability thread
started 2017-01-25T21:11:13.547+0000 I JOURNAL [journal writer]
Journal writer thread started 2017-01-25T21:11:13.568+0000 I CONTROL
[initandlisten] MongoDB starting : pid=1 port=27017 dbpath=/data/db
64-bit host=150c248f4cc7 2017-01-25T21:11:13.568+0000 I CONTROL
[initandlisten] db version v3.0.2 2017-01-25T21:11:13.568+0000 I
CONTROL [initandlisten] git version:
6201872043ecbbc0a4cc169b5482dcf385fc464f 2017-01-25T21:11:13.569+0000
I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.1e 11 Feb 2013
2017-01-25T21:11:13.569+0000 I CONTROL [initandlisten] build info:
Linux ip-10-171-120-232 3.2.0-4-amd64 #1 SMP Debian 3.2.46-1 x86_64
BOOST_LIB_VERSION=1_49 2017-01-25T21:11:13.569+0000 I CONTROL
[initandlisten] allocator: tcmalloc 2017-01-25T21:11:13.569+0000 I
CONTROL [initandlisten] options: {} 2017-01-25T21:11:13.573+0000 I
NETWORK [initandlisten] waiting for connections on port 27017
2017-01-25T21:11:17.843+0000 I NETWORK [initandlisten] connection
accepted from 172.20.0.1:44148 #1 (1 connection now open)
2017-01-25T21:11:17.843+0000 I NETWORK [initandlisten] connection
accepted from 172.20.0.1:44146 #2 (2 connections now open)
2017-01-25T21:11:17.853+0000 I NETWORK [conn2] end connection
172.20.0.1:44146 (1 connection now open) 2017-01-25T21:11:17.998+0000 I NETWORK [conn1] end connection 172.20.0.1:44148 (0 connections now
open)
So it looks that my mongodb is up running. When I in in my node application try to access it I get.
{ MongoError: failed to connect to server [localhost:27017] on first
connect
at Pool. (/usr/src/app/node_modules/mongodb-core/lib/topologies/server.js:326:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection. (/usr/src/app/node_modules/mongodb-core/lib/connection/pool.js:270:12)
at Object.onceWrapper (events.js:290:19)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket. (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:175:49)
at Object.onceWrapper (events.js:290:19)
at emitOne (events.js:96:13) name: 'MongoError', message: 'failed to connect to server [localhost:27017] on first connect' }
My code trying to access the mongodb
const express = require('express');
const gh = require('./src/fetch');
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/myApp';
// Constants
const PORT = 8888;
// App
const app = express();
app.get('/', function (req, res) {
MongoClient.connect(url, function (err, db) {
if (err) {
console.log(err);
} else {
console.log("Connected correctly to server");
db.close();
}
});
res.send('Hello world\n');
});
app.listen(PORT);
console.log('Running on http://localhost:' + PORT);
My docker-compose looks like this.
version: '2'
services:
web:
image: gh-api
ports:
- "8888:8888"
environment:
- KEY=abc
restart: always
links:
- mongoDB
depends_on:
- mongoDB
mongoDB:
image: mongo:3.0.2
ports:
- "27017:27017"
Dockerfile for gh-api
FROM node:7.4-onbuild
EXPOSE 8888
Could you change url to your mongodb from:
const url = 'mongodb://localhost:27017/myApp';
to
const url = 'mongodb://mongoDB/myApp';
I had similar issue with my demo blog application and with that change application started working.
Edit
The best explanation that I could found is explanation of docker-compose links.
Containers for the linked service will be reachable at a hostname
identical to the alias, or the service name if no alias was specified.
So in order to access mongoDB container from web container you should use mongoDB as host name in web container.
It looks like you are trying to access MongoDB over HTTP on the native driver port.
That port is to be used by the mongo driver. If you really want/need to access the rest interface you have to use port 28017 and start mongo with the --rest flag. An example:
$ docker run --rm -p 28017:28017 mongo mongod --rest
To access a container from another, with docker compose use the service name, as pointed out by Ivan.
In my case everything was correctly setup just like answered in this question however I got this error caused by "boot race", basically my Node app would boot before mongo image and therefore it would try to connect to mongo before it's up and running. So I changed my connection code to retry again with something like this:
init().then((mongo) => main({ mongo })).catch(e => init())
function init(){
return MongoClient.connect(mongoConnectionURL)
}
function main({ mongo }){
const server = express()
server.listen(port, host);
}
I tought, this was supposed to be solved using depends_on property inside compose file, but as far as I understand, depends_on only makes sure to start other services, doesn't make sure they were initialized in proper order.

Mongoose - remote database connect failed

I am trying to connect to my mongo database in my remote server:
$ mongo xxx.xxx.xxx.xx:27017
But I get this error:
MongoDB shell version: 2.6.10 connecting to: xxx.xxx.xxx.xx:27017/test
2016-11-07T05:18:39.140+0000 warning: Failed to connect to
xxx.xxx.xxx.xx:27017, reason: errno:111 Connection refused
2016-11-07T05:18:39.142+0000 Error: couldn't connect to server
xxx.xxx.xxx.xx:27017 (xxx.xxx.xxx.xx), connection attempt failed at
src/mongo/shell/mongo.js:148 exception: connect failed
Any ideas why?
I even have tried to connect it with an username and password but it still fails to connect...
Run this following command :
sudo service mongodb stop
sudo rm /var/lib/mongodb/mongod.lock
sudo service mongod restart
mongo

[Error: failed to connect to [localhost:27017]] from NodeJS to mongodb

I am having problem connecting to MongoDB from NodeJS using following sample code. I tried running "mongod" with or without sudo but nodejs code still fail to connect. I am able to successfully connect to database using "mongo".
Running on : MAC OS 10.6.8
var mongoClient = require('mongodb').MongoClient;
mongoClient.connect("mongodb://localhost:27017/test", function(error, db) {
if(!error){
console.log("We are connected");
}
else
console.dir(error);
});
get following error running above code : [Error: failed to connect to [localhost:27017]]
Also tried mongoose but similar error:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log("DB connected");
// yay!
});
Output: connection error: [Error: failed to connect to [localhost:27017]]
Here is the log of mongod
mongod --help for help and startup options
2014-07-11T23:33:47.843-0700 kern.sched unavailable
2014-07-11T23:33:47.849-0700 [initandlisten] MongoDB starting : pid=29942 port=27017 dbpath=/data/db 64-bit host=usc8bcc8a0d0b1
2014-07-11T23:33:47.849-0700 [initandlisten]
2014-07-11T23:33:47.849-0700 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2014-07-11T23:33:47.849-0700 [initandlisten] db version v2.6.3
2014-07-11T23:33:47.849-0700 [initandlisten] git version: nogitversion
2014-07-11T23:33:47.849-0700 [initandlisten] build info: Darwin usc8bcc8a0d0b1 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386 BOOST_LIB_VERSION=1_49
2014-07-11T23:33:47.849-0700 [initandlisten] allocator: system
2014-07-11T23:33:47.849-0700 [initandlisten] options: {}
2014-07-11T23:33:47.850-0700 [initandlisten] journal dir=/data/db/journal
2014-07-11T23:33:47.850-0700 [initandlisten] recover : no journal files present, no recovery needed
2014-07-11T23:33:47.901-0700 [initandlisten] waiting for connections on port 27017
2014-07-11T23:34:47.901-0700 [clientcursormon] mem (MB) res:48 virt:2810
2014-07-11T23:34:47.901-0700 [clientcursormon] mapped (incl journal view):320
2014-07-11T23:34:47.901-0700 [clientcursormon] connections:0
Never mind, I was able to resolve the issue by using 127.0.0.1 instead of localhost, not sure why I have to use ip address. My tomcat, apache, redis, and even node server all works using localhost but not the mongodb. Is there is config I need change to make it work using local host?
Try adding 127.0.0.1 localhost in /private/etc/hosts file.
This issue can occur if your mongoDBwasnot shutdown properly
Mongodb can't connect to localhost but can connect to localhost's IP address
Start your mongoDB Server using follwoingcommand and then try same ./mongod --bind_ip localhost
yes , I came across this error too, and my hosts is as follow:
127.0.0.1 xxxxxx(the ip of my computer)
and when I ran npm start in express project, it got an error like that . After I tried to change the mapping of 127.0.0.1 to localhost, it had no error.
The first time, I made the obvious mistake that mongod (the mongo Server) was not even running.
The second time, I had both the Server (mongod) and the Client (mongo) running on my Windows; in separate Command Prompts (of course mongo running first). mongod and/or its Command Prompt was "hung up" (i.e. the last line only said this, and the last line remained like this despite attempts to connections:)
2017-06-20T12:31:02.937-0600 I NETWORK [thread1] waiting for connections on port 27017
I clicked in the Command Prompt pressed the space-bar to "kick it" , and the Command Prompt printed lines like these:
2017-06-20T12:31:48.517-0600 I NETWORK [thread1] connection accepted from 127.0.0.1:50260 #1 (1 connection now open)
Which worked!
Somebody on Github found a solution:
Instead of writing:
Mongoose.connect(config.database.url);
Write:
Mongoose.connect(config.database.url, {
keepAlive: true,
reconnectTries: Number.MAX_VALUE,
useMongoClient: true
});
(Source https://github.com/Automattic/mongoose/issues/5399)

Resources