Friday, September 13, 2019

NodeJS Forever

The purpose of NodeJS Forever is to keep a child process (such as your node.js web server) running continuously and automatically restart it when it exits unexpectedly. Forever basically allows you to run your NodeJS application as a process.
Reference: https://stackoverflow.com/a/32944853

A simple CLI tool for ensuring that a given script runs continuously (i.e. forever)
https://github.com/foreversd/forever#readme


A simple example to start and manage Forever
> forever start -a --minUptime 1000 --spinSleepTime 2000 --uid yourapp-stg yourapp.js

-a                        append to logs
--minUptime       1000     wait a second before considering restart
--spinSleepTime 2000    wait two seconds before restarting
--uid                   name the forever process

List all running Forever processes
> forever list
info:    Forever processes running
data:    uid   command       script                          forever pid   id          logfile                            uptime
data:    [0]   yourapp-stg   /usr/bin/node start.js   1668             23197   /home/yourapp/.forever/yourapp.log     0:1:20:14.94

You can restart and stop by name or uid.
Note: uid is incremental, so it may not always be the same number.

> forever restart yourapp-stg
> forever restart 0

> forever stop yourapp-stg
> forever stop 0

And since you may not want to type or remember all these options, create some helper shell scripts

> start-yourapp.sh
#!/bin/bash
forever start -a --minUptime 1000 --spinSleepTime 2000 --uid yourapp-stg yourapp.js

> restart-yourapp.sh
#!/bin/bash
forever restart yourapp-stg


While forever will keep your NodeJS process running, it will not start on reboot.
One simple method to ensure your NodeJS runs on reboot, is to add crontab entry to your forever process.

Create a crontab entry as the user your app runs as
> crontab -e

@reboot /bin/sh /home/yourapp/crontab-reboot.sh

And create the reboot script
> crontab-reboot.sh
#!/bin/bash

# export path to NodeJS, Forever
export PATH=/usr/local/bin:$PATH

# cd to location of script
cd /home/yourapp || exit

# run script, in this case Forever
forever start -a --minUptime 1000 --spinSleepTime 2000 --uid yourapp start.js

So now you application will run .. Forever .. yup.

-End of Document-
Thanks for reading