Keep Your Node.js Server Running Forever
Or any Node process for that matter…
It is fairly common to run into the situation when building applications or scripts where you need your Node processes to continue to run in perpetuity unless you otherwise stop them.
For example, you write a script that makes API calls to a service to collect data, perhaps it makes calculations and performs actions based on those results or maybe it is just scraping and storing the data. You may want to set that script up on a server in the cloud and just let it run. Another example and one I think may be arguably more valuable is in running Node server applications. If you have experience running a non-trivial Express microservice you may have run into situations where your server experiences an uncaught error in processing causing the Node process to exit, leaving your server dead and downstream service consumers in the dark.
The following article explains a few brief ways to keep your script or server running forever despite uncaught errors that may occur and kill the process, so you can enjoy peace-of-mind knowing your software is continuing to run.
Async Forever
Have a Node script that runs through operations and you want to have that script run over and over? async
forever is your friend as it simplifies this use case without you having to write a complicated while-loop. Here’s an example where run()
is your script’s main function (server programs are already setup to run this cyclic forever-process under-the-hood):
This will help you run your code continuously but it won’t protect it from errors that you haven’t explicitly caught.
Using Cluster for Uncaught Errors
Using the cluster
package will offer a lot of protection against uncaught errors in your script or in your server. A typical method for guarding against uncaught server errors is with error middleware, although not all middleware is airtight — especially if it is too complex or is written poorly — and especially in a large service where an error occurring and not propagating all the way up to the middleware can and probably will happen at some point. Guard against this by using cluster
to setup a master process that spawns your server as a worker process. If the worker process crashes the master can easily spawn it anew.
By using this method of running your server application with cluster
or running your node script by using a combination of async
forever along with cluster
you can be sure your code will continue to run regardless of errors popping up that you haven’t accounted for.
While I have found that this simple method can keep even a production service up and running by simply starting the process with a manual node <my server file>.js
inside the machine it’s running on, I recommend using a higher level process manager such as Supervisord to make sure the process is restarted if the machine reboots or the container cycles.
Happy Coding!