MySql2 driver doesn't close connection pool

42 views Asked by At

There is a web application that was created with the Node.js + Express + MySQL (mysql2/promise) stack. I need to close the connection pool when the application receives a SIGTERM signal.

Here is a minimal reproducible example of the problematic code:

import mysql from 'mysql2/promise'
import express from 'express';
import https from 'https';

const connectionPool = mysql.createPool({
    password: 'some_password',
    user: 'some_user',
    host: 'localhost',
    port: 3306
});
const app = express();
const httpsServer = https.createServer(app);

async function initDataBase() {
    await connectionPool.query('CREATE DATABASE IF NOT EXISTS test;');
}

initDataBase().then(() => {
    app.use(express.json());
    app.get('/hello', (req, res) => res.send('Hi!'));
    app.listen(8080, () => console.log('Server was started successfully.'));
});

process.on('SIGINT', () => {
    console.log('SIGINT signal was received.');
    httpsServer.close(() => {
        console.log('http server has closed.');
        connectionPool.end(() => {
            console.log('connection pool has closed.');
            process.exit(0);
        });
    });
});

When closing the application with ctrl + c, the console does not display the 'connection pool has closed' entry. The application freezes after printing 'http server has closed.' Upon pressing ctrl + c again, it produces an error: 'Can't add new command when the connection is in a closed state.'

0

There are 0 answers