How to keep node.js running on shared hosting
Building a node.js application is one thing. Making sure it is always operational is another. This article details a simple approach to keep your node.js application online on a shared host. These are the three steps to follow:
- Write robust node.js code with failure and error handling routines
- Use PM2 process manager to catch and restart unexpected failure
- Configure crontab to periodically check and restart
Write robust node.js code
First things first. Write your code the recommended node.js way. Use asynchronous calls for functions that can take some time. Catch error situations where possible. When you do experience your application halting, find out why. Then catch the situation by code, if possible.
Use PM2 process manager
PM2 is a production process manager for node.js. PM2 monitors your application and automatically restarts it when an unexpected event made it crash. Install PM2 using
npm install pm2
and use it to start your application
pm2 start myapp.js
Once started like this, PM2 lists all running applications (yes, you can give it multiple applications if you like!) and shows you details of each of them
pm2 show <app-id>
So far so good. Now what happens when the server running your application reboots or, even worse, crashes? Right, the PM2 process is killed and will not be restarted automatically. The same goes for your application.
In order to handle that situation as well, a third measure is needed.
A crontab you can see as a list of commands that need to be run at specified times. These times can either be fixed intervals (let's say eg every 5 minutes), or system events (eg server reboot).
Crontab is used here to
- check periodically and at server reboot the status of the application, and
- restart the PM2 process in case it was found dead
Start by writing a script that verifies the running state of your application:
#!/bin/bash ps cax | grep node > /dev/null if [ $? -eq 0 ]; then echo "Process is running." >/dev/null 2>&1 else echo "Process is not running." PATH=$PATH:/usr/local/bin pm2 start /path/to/your/node/application fi
This code will check if a process named 'node' is running and, if not, restarts it using pm2. Now add periodic execution of this code either using cPanel as a Cron Job running every 5 minutes:
Or edit crontab directly from the terminal to add the same line:
By implementing these three measures, we make sure our node.js application keeps running. In case of unexpected failure, PM2 will catch it and restart. In case of server downtime or reboot, a custom script running periodically catches the situation and restarts the application automatically.
On top of this all, you can configure cPanel to send emails when a cron job produces output. This way, you get a notification when the application is down and being restarted.