I have been looking for the best way to make a cloud server with Ubuntu when it restarts, or if it crashes for any reason and then gets up again, the nodeJs server that I have running on it automatically resumes.
To keep node running I do it with Forever, and to do what I'm asking about, I've found two ways:
- Crontab:
Using Crontab as follows:
$ crontab -u myuser -e
and in the editor that opens by adding the following line
@reboot /usr/local/bin/forever start /your/path/to/your/app.js
- Adding file to $ cd /etc/init.d
Add file and change permissions as follows:
$ cd /etc/init.d
$ sudo nano nodeapps
in the editor where nodeapp is created we put the following line:
sudo forever start /ruta/al/script/principal/de/la/app.js
We give execution permissions:
$ sudo chmod +x nodeapps
and add the script to boot:
$ sudo update-rc.d nodeapps defaults
Well, my question is which of these ways would be more stable, or if you have any other better way to do it?
This is done with PM2 which is the process manager for Nodejs. First you install it:
Once installed you can start your app.js with PM2 (from the folder where app.js is located)
With your processes running, started by PM2, you can now automatically generate the corresponding script, without having to worry about programming, since PM2 will generate it for you. To do this we have the following command:
Finally you save this process so that every time your machine restarts app.js does too:
And ready. You can now reboot your machine and everything will work
Some PM2 commands that will be useful to you:
The system looks more or less like this:
: