Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knex:Error Pool2 - Error: connect ECONNREFUSED

I am working with Node.js, Express.js, Bookshelf.js and Knex.js

I am getting following error with default knex pool definition.

Knex:Error Pool2 - Error: connect ECONNREFUSED

That is with following knex definition (default pool.min value is 2)

var knex = require('knex')({
            client: 'mysql',
            connection: config.connection,
});

I get error

Knex:Error Pool2 - Error: connect ECONNREFUSED
Knex:Error Pool2 - Error: connect ECONNREFUSED

Where as it works fine with following definition.

var knex = require('knex')({
            client: 'mysql',
            connection: config.connection,
            pool: {
                    min: 0,
                    max: 10
            }
});

I noticed that the error is printed n number of times where n in pool.min value.

Can someone please tell me why this is happening. Although, error is resolved but since I am newbie, I am not able to understand why this is happening.

like image 480
Rusty Avatar asked Nov 20 '15 09:11

Rusty


1 Answers

ECONNREFUSED is returned by the connect() system call when the remote system or service is either not listening on the specified port or a firewall between you is making it appear so.

Basically, knex is unable to connect to the database server. The reason why you don't get the error with pool.min is 0 is because the pool2 library is satisfied with zero active connections and will not attempt to connect to the database until a connection is needed by knex.


To follow up, the knex folks don't seem to care to implement this. Furthermore, the issue seems to be that the Pool2 object is destroyed when ECONNREFUSED is encountered at startup and knex is just not able to recover from it.

That being said, the issue only occurs for me at startup. If the database goes down /after/ the pool is established, knex will keep trying to connect until it comes back up. Something in either knex or the mysql client library handles the reconnect case just fine, even if ECONNREFUSED is returned. With that in mind, what I've taken to doing is this:

setTimeout(function () {
    knex.raw('SELECT 1').catch(function (error) {
        log.fatal('caught exception trying to issue database keep-alive');

        // do something fatal, like exit or cluster.worker.disconnect()
    });
}, 0);

I do this immediatey after I create the knex object. Fail fast. This works for me, but YMMV.

like image 68
diz Avatar answered Oct 06 '22 01:10

diz