0
0
Expressframework~30 mins

Graceful shutdown handling in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Graceful shutdown handling
📖 Scenario: You are building a simple Express server that needs to stop cleanly when the app is closed or restarted. This means it should finish any ongoing requests before shutting down.
🎯 Goal: Create an Express server that listens on port 3000 and implements graceful shutdown by closing the server and exiting the process when it receives a termination signal.
📋 What You'll Learn
Create an Express app with a basic route
Start the server listening on port 3000
Add a variable to hold the server instance
Implement a function to handle graceful shutdown
Listen for termination signals and call the shutdown function
💡 Why This Matters
🌍 Real World
Servers often need to stop without dropping active users or leaving resources open. Graceful shutdown helps keep apps reliable and user-friendly.
💼 Career
Understanding graceful shutdown is important for backend developers and DevOps engineers to maintain stable and maintainable server applications.
Progress0 / 4 steps
1
Create the Express app and basic route
Create an Express app by requiring express and calling it to create app. Then add a GET route on '/' that sends the text 'Server is running'.
Express
Need a hint?

Use require('express') to import Express and app.get to create a route.

2
Start the server and save the server instance
Start the server listening on port 3000 by calling app.listen(3000). Save the returned server instance in a variable called server.
Express
Need a hint?

Save the result of app.listen(3000) to server.

3
Create a graceful shutdown function
Create a function called gracefulShutdown that calls server.close() with a callback. Inside the callback, call process.exit(0) to exit the process cleanly.
Express
Need a hint?

Use server.close() with a callback that calls process.exit(0).

4
Listen for termination signals and call graceful shutdown
Use process.on to listen for the 'SIGINT' and 'SIGTERM' signals. For each, call the gracefulShutdown function.
Express
Need a hint?

Use process.on to listen for 'SIGINT' and 'SIGTERM' and call gracefulShutdown.