Last active
January 24, 2023 19:19
-
-
Save johnelliott/fee6b6344cd5d0d8ff56b5a4c143898a to your computer and use it in GitHub Desktop.
Node.js Express Graceful shutdown Kubernetes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('dotenv').config() | |
const http = require('http') | |
const express = require('express') | |
const app = express() | |
// Routes | |
app.get('/', function (req, res, next) { | |
console.log('got request') | |
setTimeout(function timeoutDone () { | |
console.log('sending response') | |
res.sendStatus(200) | |
}, 5000) | |
}) | |
app.use(function (err, req, res, next) { | |
console.log(err) | |
res.sendStatus(500) | |
}) | |
// Server | |
const host = process.env.HOST || 'localhost' | |
const port = process.env.PORT || 8080 | |
const server = http | |
.createServer(app) | |
.on('close', () => console.log('closed')) // https://nodejs.org/dist/latest-v11.x/docs/api/http.html#http_event_close | |
.listen(port, host, () => { | |
console.log(`listening on ${host}:${port}`) | |
}) | |
// shutdown handling | |
function handleShutdown (thing) { | |
console.log('got %s, starting shutdown', thing) | |
if (!server.listening) process.exit(0) | |
console.log('closing...') | |
// TODO disconnect from databases like redis | |
// https://nodejs.org/dist/latest-v11.x/docs/api/http.html#http_server_close_callback | |
// https://nodejs.org/dist/latest-v11.x/docs/api/net.html#net_server_close_callback | |
server.close(err => { | |
if (err) { | |
console.error(err) | |
return process.exit(1) | |
} | |
console.log('exiting') | |
process.exit(0) | |
}) | |
} | |
/* | |
* references: | |
* signals: http://man7.org/linux/man-pages/man7/signal.7.html | |
* node signal events: https://nodejs.org/dist/latest-v11.x/docs/api/process.html#process_signal_events | |
* kubernetes shutdown: https://cloud.google.com/blog/products/gcp/kubernetes-best-practices-terminating-with-grace | |
*/ | |
process.on('SIGINT', handleShutdown) | |
process.on('SIGTERM', handleShutdown) | |
process.on('SIGHUP', handleShutdown) // pointless? debatable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment