const server = app.listen(3000, "0.0.0.0");
process.on("SIGTERM", async () => {
server.close(async () => {
await db.end();
await redis.quit();
process.exit(0);
});
setTimeout(() => process.exit(1), 8000).unref();
});
On SIGTERM, the app should shut down cleanly, and it must finish before the stop timeout ends.
Steps on SIGTERM:
- Stop accepting new connections.
- Let in-flight requests finish. These are requests that already started.
- Close database and Redis connections.
- Flush the logs.
- Exit with code 0.
server.close stops new connections. It calls its callback once the existing connections are done.
The stop timeout: the whole shutdown must fit inside the platform's grace period. The default is 10 seconds for docker stop and 30 seconds in Kubernetes. After that, the process gets SIGKILL, which kills it at once.
So the snippet sets its own 8 second fallback timer that forces an exit. This timer matters, because idle keep-alive connections can keep server.close waiting.
Changing the grace period:
docker stop -tfor Docker.stop_grace_periodin Compose.terminationGracePeriodSecondsin Kubernetes.
- The app stops accepting new connections.
- It lets in-flight requests finish, then closes the database and cache connections.
- It must exit before the grace period ends.
- A fallback timer forces an exit if shutdown takes too long.
- You can change the grace period in Docker, Compose and Kubernetes.