How to automatically restart forever (for Node.js scripts and servers) on a system reboot

I use forever to start my Node.js scripts, to ensure that if it crashed, it would just auto-restart.

An issue arises though if the server itself reboots. Which for some reason happened on a DigitalOcean droplet I was using. So I needed to figure out a way to restart the forever process on system reboot. I couldn’t find any clear documentation, but this is the solution I finally figured out after piecing together various bits of information¬†online together. The most helpful source of this answer came from an answer on stack overflow.

First, run

crontab -u root -e

then after all the comments add this content:

Some key points here:

  1. you can explicitly set any environment variables you need in here for the script to work
  2. you must include your path to your Node.js executable. This PATH seems to normally load only after the crontab is run.

This certainly helps make your Node.js servers and scripts much more robust.

Published by


Andrew Golightly is the lead web developer here at Golightly+. He is a passionate fullstack JavaScript developer. He also runs an Empath Community.

Leave a Reply

Your email address will not be published. Required fields are marked *