MongoError: connection 0 to localhost:27017 timed out - node.js

events.js:141
throw er; // Unhandled 'error' event
MongoError: connection 0 to localhost:27017 timed out
at Function.MongoError.create (/home/ubuntu/scripts/node_modules/mongodb-core/lib/error.js:29:11)
at Socket.<anonymous> (/home/ubuntu/scripts/node_modules/mongodb-core/lib/connection/connection.js:184:20)
at Socket.g (events.js:260:16)
at emitNone (events.js:67:13)
at Socket.emit (events.js:166:7)
at Socket._onTimeout (net.js:318:8)
at _runOnTimeout (timers.js:524:11)
at _makeTimerTimeout (timers.js:515:3)
at Timer.unrefTimeout (timers.js:584:5)
Well there is no error during connection, but when try to save some models/collections it runs for a while and then it throws this error.
BTW I also have another node process connected to the same mongodb server. Any help is highly appreciated.

const mongoose = require('mongoose');
const option = {
socketTimeoutMS: 30000,
keepAlive: true,
reconnectTries: 30000
};
const mongoURI = process.env.MONGODB_URI;
mongoose.connect(mongoURI, option).then(function(){
//connected successfully
}, function(err) {
//err handle
});

Your query is taking a long time. And mongo itself has a default time out set. So it times out, if the query takes longer than the timeout time.

you have to use this configs on your connection:
keepAlive: 300000, connectTimeoutMS: 30000

If you are sure that you exported port -p 27017:2017 and it still doesn't work.
Check your VPN if it is not blocking Local Network sharing.

Related

ioredis Error: connect ETIMEDOUT - Can't get connection to local redis server

Problem
On my node.js backend, I initialized a redis server:
const options = {
host: process.env.REDIS_HOST, // localhost
port: process.env.REDIS_PORT, // 6379 Redis standard port
db: 0,
// reconnect after
retryStrategy: times => Math.min(times * 50, 2000),
tls: {}
};
export const redis = new Redis(options);
Unfortunately, I always get this error message:
[ioredis] Unhandled error event: Error: connect ETIMEDOUT
at TLSSocket.<anonymous> (/home/pascal/vipfy/vipfy-backend/node_modules/ioredis/built/redis.js:298:31)
at Object.onceWrapper (events.js:273:13)
at TLSSocket.emit (events.js:182:13)
at TLSSocket.EventEmitter.emit (domain.js:442:20)
at TLSSocket.Socket._onTimeout (net.js:449:8)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)
I installed redis locally and use the redis-cli to ping the local server, no password is set. It always gives a positive answer, but I can't seem to be able to reach it via ioredis. Anybody an idea?
Make sure your redis server is running. You just try without options params, so it will try to connect your localhost redis automatically by host as localhost and port as 6379.
redis = new Redis();
If you don't have any specific advantage try following, I am using following one and works well.
Package : "redis": "^2.8.0"
Code :
var redis = require('redis');
var redis_conn = redis.createClient();
redis_conn.set("key", "val");

node express-myconnection mysql pool : connection closed by server

I have a node server that create a connection pool to mysql, if there has been no activity for a period of time the connection is closed by server and and further access throws an error. Not sure where to go with this, have researched a number of forums with little luck.
var mysql = require('mysql');
var connection = require('express-myconnection');
// DB connection
var dbOptions = {
host: 'localhost',
user: 'admin',
password: 'admin',
port: 3306,
database: 'data',
multipleStatements: true,
connectionLimit: 20
};
app.use(connection(mysql, dbOptions, pool));
Error
Whoops there is an uncaught error Error: Connection lost: The server closed the connection.
at Protocol.end (/opt/www/CMI_intern_2/node_modules/mysql/lib/protocol/Protocol.js:109:13)
at Socket.<anonymous> (/opt/www/CMI_intern_2/node_modules/mysql/lib/Connection.js:109:28)
at emitNone (events.js:72:20)
at Socket.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:921:12)
at nextTickCallbackWith2Args (node.js:442:9)
at process._tickCallback (node.js:356:17)
Connection pool works fine, there was a hidden database connection in some old code that was the root cause. Non issue.
actually, if someone experiences those errors while calling localhost adding database option
socketPath: '/var/run/mysqld/mysqld.sock'
solve this problem

NodeJS server closes connection after idling for a few hours

This question has been re-asked at past years, however solutions are either using deprecated methods or are not clear.
NodeJS server (running on CentOS) after being idle for some hours, usually at night, closes its connection and shuts down probably because it loses its connection with MySQL.
Error: Connection lost: The server closed the connection.
at Protocol.end (/home/s/prcrm/node_modules/mysql/lib/protocol/Protocol.js:109:13)
at Socket.<anonymous> (/home/s/prcrm/node_modules/mysql/lib/Connection.js:115:28)
at emitNone (events.js:91:20)
at Socket.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:975:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
DB Configuration
function DB( host, user, password, database ) {
this.host = host;
this.user = user;
this.password = password;
this.database = database;
this.connection = mysql.createConnection({
host: this.host,
user: this.user,
password: this.password,
database: this.database
});
this.connection.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
Versions
Node.js: 6.4.0
Express: 4.13.4
MySQL: 10.0.29-MariaDB MariaDB Server
CentOS: 6.8 (Final)
Any suggestions or guidance of how to keep MySQL connection alive (without being quick&dirty) when server is idling, supposing that this causes the problem?

MongoDB mLab mongoose Node.js driver - connection timeout after a period of idle time?

I have a simple Node.js that uses mongoose to connect with Mongo database hosted on mLab.
Everything seems working just fine: adding new records, querying for existing stuff.
Only sometimes, after some period of inactivity, when I look at the console I see the following:
events.js:160
throw er; // Unhandled 'error' event
^
Error: connection timeout
at Db.<anonymous> (___PATH___/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:168:17)
at emitTwo (events.js:106:13)
at Db.emit (events.js:191:7)
at Server.listener (___PATH___/node_modules/mongodb/lib/db.js:1786:14)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at Server.<anonymous> (___PATH___/node_modules/mongodb/lib/server.js:274:14)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at Pool.<anonymous> (___PATH___/node_modules/mongodb-core/lib/topologies/server.js:334:12)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (___PATH___/node_modules/mongodb-core/lib/connection/pool.js:270:12)
at Connection.g (events.js:292:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
Right now it doesn't matter that much to me - I can always restart the app. I'm worried that in production it will cause a lot of headaches so I preemptively ask what's the issue here?
Note that initially everything is working fine, it after some time when I get Error: connection timeout
Sample Connection code for Mongo-Node using Mongoose
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const options = {
useMongoClient: true,
reconnectTries: 5000,
reconnectInterval: 0,
socketTimeoutMS: 100000,
connectTimeoutMS: 100000
}
mongoose.connect(mongodb://........, options);
var db = mongoose.connection;
db.on('error', function (error) {
console.log('Error while connecting to mongodb database:', error);
});
db.once('open', function () {
console.log('Successfully connected to mongodb database');
});
db.on('disconnected', function () {
//Reconnect on timeout
mongoose.connect(mongodb://........, options);
db = mongoose.connection;
});
it seems that there is fluctuation in your internet connection. Maybe this is the reason of connection timeout.
you can handle it by setting the timeout.
As below :
var timeout = require('connect-timeout');
app.use(timeout('5s'));`
in your app.js file
Replace your mongoose connection setting by this code:
var mongoose = require('mongoose');
/*
* Mongoose by default sets the auto_reconnect option to true.
* We recommend setting socket options at both the server and replica set level.
* We recommend a 30 second connection timeout because it allows for
* plenty of time in most operating environments.
*/
var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
var mongodbUri = 'mongodb://user:pass#host:port/db';
mongoose.connect(mongodbUri, options);
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function() {
// Wait for the database connection to establish, then start the app.
});

Mongoose gives error while connecting using mongolab uri ?

It gives the following error-
mongoose connection error: { [MongoError: connect EINVAL] name: 'MongoError', message: 'connect EINVAL' }
/home/user/Documents/oes/node_modules/connect-mongo/node_modules/mongodb/lib/server.js:228
process.nextTick(function() { throw err; })
^
Error: connect EINVAL
at errnoException (net.js:905:11)
at connect (net.js:767:19)
at net.js:846:9
at asyncCallback (dns.js:68:16)
at Object.onanswer [as oncomplete] (dns.js:121:9)
14 Jun 18:04:11 - [nodemon] app crashed - waiting for file changes before starting...
This is a very old problem, But as no one has yet answered it.
We often see that users have problems connecting to MongoLab using the Mongoose driver. The root cause is almost always incorrect configuration of the driver, particularly around timeouts. The following is a connection example using the MongoLab-recommended driver options:
// mongoose 4.3.x
var mongoose = require('mongoose');
/*
* Mongoose by default sets the auto_reconnect option to true.
* We recommend setting socket options at both the server and replica set level.
* We recommend a 30 second connection timeout because it allows for
* plenty of time in most operating environments.
*/
var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
var mongodbUri = 'mongodb://user:pass#host:port/db';
mongoose.connect(mongodbUri, options);
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function() {
// Wait for the database connection to establish, then start the app.
});
If this doesn't help, please ensure your password or username doesn't has any special character, Try to connect it via CMD first.
Hope I helped :)

Resources