How to restart NodeJS with cPanel - node.js

I need to know what to use from root side of cPanel based server to restart NodeJS app, for example, if process terminated now for some reasons NodeJS app will not start until I manually start it, same if server restart I need manually to restart it.
Also, this is case for several accounts on server, command should allow more apps to be restarted/started.
Any help would be great

Here is an automated way to do the it:
- Find if node server [eq. server.js] is running or not.
- If server is not running, restart by "nodemon server.js".
- Else if server is running, do nothing.
You can code this in bash script [sample code below] and set up a CRON job in your cpanel to run it after a particular time.
#!/bin/bash
NAME="server.js" # nodejs script's name here
RUN=`pgrep -f $NAME`
if [ "$RUN" == "" ]; then
nodemon server.js
else
echo "Script is running"
fi

I'd recommend running your node app using PM2.
npm install pm2 -g
pm2 start app.js
pm2 restart app
If you are using node or nodemon on Linux machine I'd recommend using PM2 to manage the service. It is a lot more stable that nodemon and offers other production level features like console.log to console.error file and
https://pm2.io/doc/en/runtime/features/commands-cheatsheet/

I just used a crone job to run the following command once every 5mins
~/bin/node ~/backends/api/app.js
I was having problems with nodemon, it was saying it's not a command blah blah so I thought of just directing straight to node and directly to my app.
This is working for my use case coz the app bails if the addr is being used. So if it crashed then it will restart it since it won't occupy the addr.

Related

PM2 to start multiple Node Applications with npm start on boot(using raspberry pi)

How can I run multiple nodejs applications using command npm start in different directories using pm2 on boot? Also how do i setup them to start again if any error occurs?
I figured out how to start npm start with pm2 using - "pm2 start npm -- start"
but I don't understand how to set up them to boot.
Based on my research "pm2 startup" gives the command to setup startup which I passed as it is in the terminal.
How do I set up the rest?
Thanks,
If you've already got the part where pm2 automatically starts when you reboot, that's good.
You then need to add each of your apps to pm2.
Go into each of your project directories and run
pm2 start your_file.js --name=my_app, where your_file.js is the file you would use to start with regular node. (ie: node server.js, or node index.js, etc.) and my_app is a friendly name that you will see with pm2 status and can use to apply future commands to.
This should start your app. If you run pm2 status it is hopefully in the "running" state.
To save it so that it automatically gets booted when you reboot or restart pm2 you need to run pm2 save whenever you change app configurations.
You can do this for as many apps as you need to start.

Amazon EC2 NodeJS server stops itself after 2 days even after using sudo nohup

I have my app running on http://talkwithstranger.com/ and I have deployed it on AWS EC2. I use this command
sudo nohup node index.js &
To continue running my Node JS server even if I close my terminal and exit my SSH.
However, after 2 days everytime I wake up and I find out that the node server itself stops automatically. I checked the running processes by using
ps -ef
and my node script is not there.
Google Chrome say site DNS not found, because NodeJS Express is not running of course to serve my html file, but why it stops itself?
What is causing this unexpected shutdown of my server after every 2 days? I have to manually run nohup again to run it again.
Does nohup has a time to expire or something ?
You should run node.js using a service / process manager. You can use something basic such as forever or supervisord but I would actually advise you to take a look at PM2.
It can do a lot of things - one of them being that it manages your process, makes sure it keeps running, restarts it when it fails, manages the logs, etc. You can also have it autostart when you restart the server.
It becomes really powerful in combination with https://pm2.io, because this enables you to monitor your server's metrics such as CPU and memory remotely and see whether exceptions happened, and much more (such as even remotely updating the software by pulling from git). However, they no longer offer a free plan unfortunately - their plans now start at $79/month, which is a pity. But don't worry, the PM2 application itself is still free and open source, only the monitoring costs money.
Basic usage of PM2:
npm install -g pm2
...to install PM2.
pm2 start my_script.js
Starts a script and lets it run in background.
pm2 status
Shows the status of any running scripts.
pm2 restart all
Restarts all running scripts.
pm2 kill
Stops all scripts and completely shuts down the PM2 daemon.
pm2 monit
Monitors CPU/RAM usage and shows it.
pm2 logs
Shows the last 20 output and error log lines and starts streaming live logs to the console. The logs are stored in the folder ~/.pm2/logs.
Using PM2, your script will not stop - at most, it will restart. And if it does you will be able to more easily understand why because you can easily access logs and watch what happenes with memory usage, etc.
Extra tips:
To avoid filling up the harddisk with logfiles, I recommend installing the module pm2-logrotate:
pm2 install pm2-logrotate
To automatically launch PM2 with the same script on startup when the server starts, you can first save the current configuration:
pm2 save
...and then use the following command to install a startup script - follow the instructions displayed, which will be different based on the exact OS you are using:
pm2 startup
To use PM2 in a more advanced way with multiple processes, custom environment variables, etc., take a look at ecosystem files.
You can try forever.Install using the following command.
npm install -g forever
Then just start forever:
forever start index.js
Another better option for production use is pm2.You can install pm2 with below command
npm install -g pm2
# or
yarn global add pm2
start server
pm2 start index.js
The best thing is you can achieve load balancing with pm2(utilize all available CPU)
pm2 start index.js -i max
For more info, you can visit pm2 documentation page.

deploying nodejs and mongoose app in aws

I'm new to aws and recently I have been able to install node, mongod and also, FTPed project file to the server.
For mongodb,
I'm doing mongo in a separate terminal tab and starting service in another tab. I want to know how can I keep the mongo service running.
For node app,
Right now i'm doing node app in the server. How can I keep it alive too ?
Now the problem, is I open the browser with publicip:portno but nothing happens. How can I locate app and run it in the browser.
my app structure is
/
node
mongo
server.js and app related files
Using the Linux/Unix nohup command allows you to start commands that ignore the signals associated with the controlling terminal process terminating (SIGHUP). Adding the & to the command allows that command to run in the background and sending the output to /dev/null will ensure that your disk does not fill up with unnecessary log output. Here are some commands that should work:
nohup mongod >/dev/null &
node server.js >/dev/null &
This is more of a Linux/Unix command line issue I think. You can use the node module called forever to run your Node.js process in the background easily.
npm install -g forever
forever start YourScript.js
You can place an & at the end of the mongod command to place it in the background.
Ensure that in your node app you have the command app.listen("port number");
This is the "port number" that you should be using in your browser to render the page with the elastic IP from your AWS instance. Make sure that your elastic IP is configured to accept inbound requests.
To keep the service/app running in the background you can run the screen command then launch ur app/service (e.g. mongod OR node app.js). In the same terminal that your app is running press control + a + d, you should see
(detached)
printed on your screen.
This should keep your app/service running in the background.

How do I leave Node.js server on EC2 running forever?

As you can tell by my question, I'm new to this...
I built my first website, I set up my first Node.js server to serve it and then pushed everything live on EC2.
I tested everything on my EC2 IP address and everything seems to be working.
Now up until now, I've been testing my app locally so it makes sense that whenever I closed the terminal, app.js would stop running so nothing would be served on localhost.
Now that my server is on EC2, the same thing happens ("obviously" one could say..) whenever I close my terminal.
So my question is how do I keep my Node.js server running on EC2 for like... forever..so that my site stays live.. forever :)
I read something about a node module called "forever" but I'm wondering (being new and all..) why isn't this "forever" functionality a default setting of the Node.js-EC2 system ?
I mean, correct me if I'm wrong, but isn't the whole point of setting up a web server and pushing it live to have it stay live forever? Isn't that what servers are supposed to do anyway (infinitely listening for requests) ? And if that's the case why do we need extra modules/settings to achieve that ?
Thanks for your help.. As you can tell I'm not only looking for a solution but an explanation as well because I got really confused.. :-)
EDIT (a few details you might need) - After installing my app on EC2 these are the steps that I follow on the terminal (The app is running on Amazon Linux by the way) :
I type ssh -i xxxxxxxxxxx.pem ec2-user#ec2-xx-xx-xx-x.eu-west-1.compute.amazonaws.com on the
terminal
After logging onto the Amazon machine I then go to the relevant folder and execute node app.js
There are 3 folders in the machine : node, node_modules and *name of my app*
app.js resides in *name of my app*
After that, the site goes live on my EC2 IP
Once I close the terminal, everything is switched off
Before you invoke Node.js, run the command:
screen
This will create a persistent environment which will allow your process to keep running after you disconnect.
When you reconnect, you can use this command to reconnect to that environment:
screen -r
Here's a random link to learn more about screen:
http://www.rackaid.com/blog/linux-screen-tutorial-and-how-to/
However, this won't help you if your EC2 instance restarts. There are many different ways to do that. Adding your startup command to /etc/rc.local is one way. Here's a link to an Amazon guide which includes adding something to /etc/rc.local.
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/building-shared-amis.html
I worked with the valid answer for a while but some times the screen just end with no reason also screen has no balance loader and others features that in a production enviroment you should care , Currently I use a npm component to do this job.
https://www.npmjs.com/package/pm2
This is so easy to use.
$ npm install pm2 -g
then just start your app with pm2 like this
$ pm2 start app.js
In the above link you can find diferents tasks to perform if you need.
Hope this help the newbies like me.
There's a better way. Use forever.js.
See it here: https://github.com/foreverjs/forever
This is a nice tutorial for how to use chkconfig with forever on CENTOS.
http://aronduby.com/starting-node-forever-scripts-at-boot-w-centos/
Or use tmux
Just Enter a tmux screen run node server
Ctrl+b Hit D and you're done.
I am very late to join the thread and seems its basic problem with every newbie. Follow the below to setup properly your first server.
follow the step on the ec2 instance(before doing this make sure you have a start script for pm2 in your package.json file):
npm install pm2 -g
pm2 startup systemd
See the output and at the last line it must be like..
You have to run this command as root. Execute the following command:
sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup
systemd -u sammy --hp /home/sammy
Take the last line command and run again with root privilege.
(before running the next command, Provide a new start script for pm2 in your package.json file e.g: "pm2-start": "pm2 start ./bin/www")
npm run pm2-start
for more info follow the link.
https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-16-04
If you are using a Ubuntu EC2, better to use the following we have been using this for the past 6 years and have had no issues with this.
sudo npm i -g forever
Now start your main, example
forever start index.js
forever start src/server.js
To stop the server use the following command
forever stop index.js
To list multiple servers running forever
forever listall

When node.js goes down, how can I bring it back up automatically?

Since node is basically a single process, when something goes terribly wrong, the whole application dies.
I now have a couple of apps built on express and I am using some manual methods to prevent extended downtimes ( process.on('uncaughtException') and a custom heartbeat monitor ).
Any suggestions from the community?
Best-practices? Frameworks?
Thanks!
A
Use something like forever
or use supervisor.
Just npm link and then sudo supervisor server.js.
These types of libraries also support hot reloading. There are some which you use from the command line and they run node services as sub processes for you. There are others which expect you to write your code to reload itself.
Ideally what you want to move towards a full blown load balancer which is failure safe. If a single node proccess in your load balancer crashes you want it to be quietly restarted and all the connections and data rescued.
Personally I would recommend supervisor for development (It's written by isaacs!) and a full blown load balancer (either nginx or node) for your real production server.
Of course your already running multiple node server processes in parallel because you care about scaling across multiple cores right ;)
Use forever.
"A simple CLI tool for ensuring that a given script runs continuously (i.e. forever)"
Just install it with npm
npm install forever
and type
forever start app.js
Try to look at forever module.
If you're using Ubuntu you can use upstart (which is installed by default).
$ cat /etc/init/my_app.conf
description "my_app"
author "me"
start on (local-filesystems and net-device-up IFACE=eth0) stop on
shutdown
respawn
exec sh -c "env NODE_ENV=production node /path/myapp/app.js >> /var/log/node.log 2>&1"
"respawn" mean that the app will be restarted if it dies.
To start the app
start my_app
For other commands
man initctl
I'll strongly recommend forever too. I used it yesterday and its a breeze:
Install npm install forever
Start your app forever start myapp.js
Check if its working forever list
Try killing your app :
ps
Get your myapp.js pid and run kill <pid
run forever list and you'll see it's running again
You can try using Fugue, a library for node.js similar to Spark or Unicorn:
https://github.com/pgte/fugue
Fugue can manage any node.js server type, not just web servers, and it's set up and configured as a node.js script, not a CLI command, so normal node.js build & deployment toolchains can use it.

Resources