Back to results for “Deployment”
Node.js › Docker & Deployment

How do you properly handle process signals (SIGTERM) inside a containerized Node.js application to support graceful shutdown?

Advanced

Answer

When Docker (or Kubernetes) stops a container, it sends SIGTERM and waits a grace period before forcibly sending SIGKILL -- a Node.js app must explicitly listen for SIGTERM and use it to stop accepting new connections, finish in-flight requests, close database connections, and then exit cleanly; without this handler, using certain process managers as PID 1 inside a container (or Node.js's own default signal handling in some configurations) can mean the signal never properly reaches or is properly handled by the application, causing abrupt connection drops.
process.on('SIGTERM', () => {
  console.log('SIGTERM received, shutting down gracefully');
  server.close(() => {
    db.disconnect().then(() => process.exit(0));
  });
  setTimeout(() => process.exit(1), 10000); // force exit if graceful shutdown hangs
});
Real-world example A Kubernetes rolling deployment used to cause a handful of dropped requests on every rollout until the team added an explicit SIGTERM handler that stops accepting new connections and drains in-flight requests before exiting, eliminating the dropped requests entirely.

Common follow-ups: Why might Node.js not receive SIGTERM correctly when run as PID 1 inside certain container configurations, and how does an init process like tini solve that?;What's an appropriate grace period to configure before Kubernetes escalates to SIGKILL?