In this quick tip, we’ll learn about using crontab
to automatically start our Node.js app, together with the use of pm2
, a production process manager for Node.js apps.
Normally as a prerequisite, you would run your Node.js server by calling such command syntax:
npm start# ornode server.js# ornpm run server# etc
With pm2
you can do so using the following syntax:
pm2 start server.js
You don’t have pm2
yet? you can simply install it with npm
:
sudo npm install -g pm2
Now that you have the command that starts your server handy, let’s keep that for the next step.
Crontab
With crontab
you can schedule cron scripts to run frequently following certain user intervals which you set while adding a new cron job. But how can we use crontab to schedule a job that starts only on system startup?
To our luck, there’s the @reboot
directive, which any events attached to it will be fired upon system startup from a reboot.
To add a new event (widely referred to as a cron job), make sure you SSH as the user that runs the node.js app normally, just in case, if for example you run the app as appuser
:
su appuser
Feel free to skip the above command if your current user is the one that usually schedules the node server.
Next, open crontab jobs:
crontab -e
If you’re running this command for the first time, it’ll prompt you to pick an editor, simply enter a number for the editor you’re most comfortable with and press enter.
Now that you’re editing a file, just get to the bottom of the file and enter a new line:
@reboot sh -c 'cd /path/to/your/app/folder && pm2 start server.js'
Note that you should replace the absolute path to your app folder in the above command. Tip: you can call realpath .
or pwd
to get the absolute path of the current working directory, in case it happens to be the app root folder.
Now save the file and exit. It should print something as follows:
crontab: installing new crontab
That means you have new or updated cron events added.
Troubleshooting
Make sure to test the scheduling command in case the automated process does not work. You can stop your server, then simply call the cammand:
sh -c 'cd /path/to/your/app/folder && pm2 start server.js'
and see if the paths are correct, pm2
binary is available in the $PATH
and whatever errors might show on screen. Once you have the command running, just paste it back to the cron event.
Something else isn’t quite working? Share with us below.