How do you implement graceful shutdown in Node.js?

A graceful shutdown stops accepting new work, allows existing requests and operations to finish within a controlled time, closes resources such as HTTP servers and database connections, and exits cleanly. Applications commonly listen for signals such as SIGTERM and SIGINT. A timeout should usually be used so shutdown cannot hang indefinitely.

Key Takeaways
  • Listen for shutdown signals.
  • Stop accepting new work.
  • Close servers and resources cleanly.
  • Use a shutdown timeout.
Knowledge Check

Which signal is commonly used by container orchestrators to request graceful termination?