Recently, I encountered node application always crash. I tried to avoid the crash and handle the error in code but it’s not sufficiency, so I ended up decided to create a schedule in our server to check if the node application service running. If it does not run we’re run it.
I’ll divide the the task into two steps. First, create a bash script to check the node application. Second, create a cron schedule.
Now let’s assume that you have a node application which locate in /home/user/example_app/index.js
1. Create a bash script:
##cd to application directory
– cd /home/user/example_app/
##create a run_node.sh file
– sudo touch run_node.sh
##give the permission for file to executable
– sudo chmod a+x
##open the file in vim text editor
– sudo vim run_node.sh
## and copy the following code, the script below check if node application is running, if it not then run it.
#!/bin/sh
APP_PATH= “/home/user/example_app/”
NAME=”index.js”RESULT=`pgrep -f $NAME`
if [ “${RESULT:-null}” = null ]; then
nohup node $APP_PATH$NAME &
fi
2. Create a cron schedule:
## Check your cron task on current user
– crontab -l
## Open new config
– crontab -e
## Add the following config
*/10 * * * * cd /home/user/example_app && sudo mkdir -p cron-log && sudo sh run_node.sh>>cron-log/`date +\%Y\%m\%d`-cron.log
## The above line do three things, go to application folder, create a cron-log folder if not exists, then run our bash script to check the node application and out put the error in cron-log folder.
## Restart cron
– sudo service cron restart (Ubuntu) or sudo service crond restart (centOS)
Check the screenshot below:
#run_node.sh
#crontab -e
Leave a comment