DEV Community

Dzung Nguyen
Dzung Nguyen

Posted on

Graceful Shutdown in Node.js Express πŸš€

πŸ’Ž When running an Express server, shutting it down gracefully ensures that ongoing requests complete and resources like database connections are properly cleaned up before the app exits.
πŸ’Ž A graceful shutdown ensures that ongoing requests finish before the app exits.

Code Example

const express = require("express"); const app = express(); const PORT = 3000; const server = app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); const shutdown = () => { console.log("\nShutting down..."); server.close(() => { console.log("Server closed. Cleanup complete."); process.exit(0); }); }; process.on("SIGINT", shutdown); process.on("SIGTERM", shutdown); 
Enter fullscreen mode Exit fullscreen mode

🌟 Key Takeaways

βœ… Listen for SIGINT/ SIGTERM signal 🚨 to trigger shutdown
βœ… Ensures active requests complete πŸ‘ before exiting
βœ… Calls server.close() to stop the server and release the port

This ensures a smooth exit without dropping connections abruptly! πŸš€βœ¨


Follow me to stay updated with my future posts:

Top comments (0)