Search code examples
mysqlnode.jsnode-mysql

Aborted connections when using node.js/mysql connectionPool


var mysql      = require('mysql');
var mysqlPool  = mysql.createPool({
  host    : 'localhost',
  user    : 'nodejs',
  password: '',
  database: 'nodejs'
});


// somewhere inside a method:
mysqlPool.getConnection(function(err, connection) {
    // do some queries

    connection.release();
});

I don't see any warnings in the output, but on the MySQL server I see aborted connections since testing with this node.js code.

Do I have to close the connection pool when I stop the node.js app?

If yes, how?


Solution

  • If you're closing you're node.js app with a Ctrl+C command, you could close your connection pool on the SIGINT event:

    process.on('SIGINT', function() {
      mysqlPool.end(function (err) {
        /* Since you're overriding the default behavior of SIGINT,
           you have to force your app to exit. You can pass it as 
           a callback to the end() function. */
        process.exit(0);
      });
    });
    

    But you could also configure your MySQL server to close idle connections, setting the server variables wait_timeout and/or interactive_timeout.

    It's up to you to decide what best fits your needs.