π 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);
π 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)