Skip to content

Commit 6b500c0

Browse files
Merge pull request #728 from PierreBrisorgueil/gracefulShutdown
feat(lib): add graceful shutdown, prevention for docker ✨
2 parents 465fd8b + eaa6a8e commit 6b500c0

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

lib/app.js

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
* Module dependencies.
33
*/
44
const chalk = require('chalk');
5-
const http = require('http');
6-
const https = require('https');
5+
const nodeHttp = require('http');
6+
const nodeHttps = require('https');
77

88
const config = require('../config');
99
const mongooseService = require('./services/mongoose');
@@ -104,6 +104,7 @@ exports.start = async () => {
104104
let db;
105105
let orm;
106106
let app;
107+
let http;
107108

108109
try {
109110
({ db, orm, app } = await bootstrap());
@@ -112,15 +113,36 @@ exports.start = async () => {
112113
}
113114

114115
try {
115-
if (config.secure && config.secure.credentials) await https.createServer(config.secure.credentials, app).listen(config.port, config.host);
116-
else await http.createServer(app).listen(config.port, config.host);
116+
if (config.secure && config.secure.credentials) http = await nodeHttps.createServer(config.secure.credentials, app).listen(config.port, config.host);
117+
else http = await nodeHttp.createServer(app).listen(config.port, config.host);
117118
logConfiguration();
118119
return {
119120
db,
120121
orm,
121122
app,
123+
http,
122124
};
123125
} catch (e) {
124126
throw new Error(e);
125127
}
126128
};
129+
130+
// Shut down the server
131+
exports.shutdown = async (server) => {
132+
try {
133+
server.then(async (value) => {
134+
await mongooseService.disconnect();
135+
// add sequelize
136+
value.http.close((err) => {
137+
console.info(chalk.yellow('Server closed'));
138+
if (err) {
139+
console.info(chalk.red('Error on server close.', err));
140+
process.exitCode = 1;
141+
}
142+
process.exit();
143+
});
144+
});
145+
} catch (e) {
146+
throw new Error(e);
147+
}
148+
};

server.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,20 @@
22
* Module dependencies.
33
*/
44

5+
const chalk = require('chalk');
56
const app = require('./lib/app');
67

7-
app.start().catch((e) => {
8+
const server = app.start().catch((e) => {
89
console.log(`server failed: ${e.message}`);
910
throw (e);
1011
});
12+
13+
process.on('SIGINT', () => {
14+
console.info(chalk.blue(' SIGINT Graceful shutdown ', new Date().toISOString()));
15+
app.shutdown(server);
16+
});
17+
18+
process.on('SIGTERM', () => {
19+
console.info(chalk.blue(' SIGTERM Graceful shutdown ', new Date().toISOString()));
20+
app.shutdown(server);
21+
});

0 commit comments

Comments
 (0)