Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save renatoargh/f84d1c3884d6c59a3a1b to your computer and use it in GitHub Desktop.
Save renatoargh/f84d1c3884d6c59a3a1b to your computer and use it in GitHub Desktop.
Restarting Your Node.js App at Reboot with Crontab

Restarting Your Node.js App at Reboot

Cronjob can prevent your application and your users from unexpected downtimes.

Create a file called starter.sh in your application's home folder and copy the following code:

#!/bin/sh

if [ $(ps -e -o uid,cmd | grep $UID | grep node | grep -v grep | wc -l | tr -s "\n") -eq 0 ]
then
        export PATH=/usr/local/bin:$PATH
        forever start --sourceDir /path/to/your/node/app main.js >> /path/to/log.txt 2>&1
fi

Where main.js should be replaced with your application's main script.

Don't forget to make starter.sh executable with chmod +x starter.sh

This useful snippet has been taken from here

To start this script at each reboot you need to edit the crontab with this command:

crontab -e and append the following code to this file

@reboot /path/to/starter.sh

Now set the absolute path to your starter.sh file.

Tip: Navigate where your starter.sh file is located and print the current directory with pwd.

Repeat the steps above for each of your domains/services.

///backed up form https://www.digitalocean.com/community/tutorials/how-to-host-multiple-node-js-applications-on-a-single-vps-with-nginx-forever-and-crontab

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment