Graceful shutdown in Node
Graceful shutdown
Before when you deploy a new version of your application with process manager or just want to shut down the server with
How do I shutdown
Handle process kill signal
Stop new requests form client
Close all data process
Exit from process
Fisrt, we need handle the signal to the application that wants to shutdown. Common signals have SIGTERM, SIGINT and so on. A signal is an asynchronous notification sent to a process or to a specific thread to notify an event that occurred. ‘SIGINT’ generated with
process.on('SIGTERM', () => { |
Second, stop new requests from client. It can be done using server.close function
process.on('SIGTERM', () => { |
Third, close all data process
process.on('SIGTERM', () => { |
Last, close all data process.As we know NodeJS will exit when EventLoop queue is empty and nothing left to do. But sometimes your application can have more functions and will not exit automatically, in this point comes our last work to do. We need to exit from process using process.exit function.
process.on('SIGTERM', () => { |
Reference
https://hackernoon.com/graceful-shutdown-in-nodejs-2f8f59d1c357
https://nodejs.org/api/process.html
https://expressjs.com/en/advanced/healthcheck-graceful-shutdown.html