Graceful shutdown on SIGINT (e.g. from 'pm2 stop').

This commit is contained in:
Mark H. Wood
2023-08-22 14:38:04 -04:00
parent 77e994dcd6
commit 6709c3bb5f
3 changed files with 122 additions and 9 deletions

View File

@@ -32,6 +32,7 @@ import isbot from 'isbot';
import { createCertificate } from 'pem';
import { createServer } from 'https';
import { json } from 'body-parser';
import { createHttpTerminator } from 'http-terminator';
import { readFileSync } from 'fs';
import { join } from 'path';
@@ -487,7 +488,7 @@ function saveToCache(req, page: any) {
*/
function hasNotSucceeded(statusCode) {
const rgx = new RegExp(/^20+/);
return !rgx.test(statusCode)
return !rgx.test(statusCode);
}
function retrieveHeaders(response) {
@@ -525,12 +526,20 @@ function serverStarted() {
* @param keys SSL credentials
*/
function createHttpsServer(keys) {
createServer({
const listener = createServer({
key: keys.serviceKey,
cert: keys.certificate
}, app).listen(environment.ui.port, environment.ui.host, () => {
serverStarted();
});
// Graceful shutdown when signalled
const terminator = createHttpTerminator({server: listener});
process.on('SIGINT', ()=> {
console.debug('Closing HTTPS server on signal');
terminator.terminate().catch(e => { console.error(e); });
console.debug('HTTPS server closed');
});
}
function run() {
@@ -539,9 +548,17 @@ function run() {
// Start up the Node server
const server = app();
server.listen(port, host, () => {
const listener = server.listen(port, host, () => {
serverStarted();
});
// Graceful shutdown when signalled
const terminator = createHttpTerminator({server: listener});
process.on('SIGINT', ()=> {
console.debug('Closing HTTP server on signal');
terminator.terminate().catch(e => { console.error(e); });
console.debug('HTTP server closed.');
});
}
function start() {