I have an nodejs server running express to server out http calls. Is there a recommended approach to shutting down the server gracefully if something bad happens? Should I leave the server running somehow?
I.E. on an uncaught exception the server just stops, I think this will kill over connected clients and not hand them back a response.
Should I:
is this proper?
process.on('exit', function () {
console.log('About to exit, waiting for remaining connections to complete');
app.close();
});
In this case an error might have been thrown leaving the server in an undefined state and the server will continue to finish up remaining connections.
Is there any good way to handle errors keep running or should I let the server die and restart?
It means that no database connection remains open and no ongoing request fails because we stop our application. Possible scenarios for a graceful web server shutdown: App gets notification to stop (received SIGTERM)
Graceful shutdown means when all your requests to the server is respond and not any data processing work left.
Graceful shutdown means that the OS (operating system) can safely shut down its processes and close all connections, however long that takes. This helps to prevent accidental data loss or other unexpected problems if the shutdown is performed intentionally by the user.
NodeJS will shutdown when it's not expecting anything to happen; While the http server is waiting on connections node stays running.
server.close([callback])
Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a
close
event. Optionally, you can pass a callback to listen for theclose
event.
After you do this the server will continue running until the last connection has finished and then shutdown gracefully.
If you don't want to wait for connections to terminate you can use socket.end()
or socket.destroy()
on your remaining connections.
See http://nodejs.org/api/net.html
process.on('exit', function () { console.log('About to exit, waiting for remaining connections to complete'); app.close(); });
This function should run when node exists and not actually tell node to exit. Here is one way you can end your process but it wouldn't end gracefully:
process.exit([code])
Ends the process with the specified code. If omitted, exit uses the 'success' code
0
.To exit with a 'failure' code:
process.exit(1);
The shell that executed node should see the exit code as1
.
See http://nodejs.org/api/process.html
I hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With