To run node.js in system boot - node.js

I have written an API using node.js. I have deployed it in the production environment. Now i ran the program(server.js) using forever.js, its working fine
But i want my node to run when the system boots itself.
I tried by creating a file in \etc\init api.conf with the following content.
start on startup
exec forever start /home/testuser/server.js
But when i reboot my system the above isn't running.Please help me solve this.
Thanks in advance.
EDIT:
Finally i tried this:
# Source function library.
. /lib/lsb/init-functions
NODE_ENV="production"
PORT="2100"
APP_DIR="/home/testuser/API/"
NODE_APP="server.js"
CONFIG_DIR="$APP_DIR"
PID_DIR="$APP_DIR/pid"
PID_FILE="$PID_DIR/server.pid"
LOG_DIR="/home/testuser/APIlogs/"
LOG_FILE="$LOG_DIR/project-debug.log"
NODE_EXEC=$(which node)
pidFile="$PID_DIR/server.pid"
logFile="$LOG_DIR/project-debug.log"
sourceDir=/home/testuser/API
coffeeFile=server.js
scriptId=$sourceDir/$coffeeFile
start() {
echo "Starting $scriptId"
# This is found in the library referenced at the top of the script
start_daemon
# Start our CoffeeScript app through forever
# Notice that we change the PATH because on reboot
# the PATH does not include the path to node.
# Launching forever or coffee with a full path
# does not work unless we set the PATH.
cd $sourceDir
PATH=/usr/local/bin:$PATH
forever start /home/testuser/API/server.js
RETVAL=$?
}
restart() {
echo -n "Restarting $scriptId"
/usr/local/bin/forever restart $scriptId
RETVAL=$?
}
stop() {
echo -n "Shutting down $scriptId"
/usr/local/bin/forever stop $scriptId
RETVAL=$?
}
status() {
echo -n "Status $scriptId"
/usr/local/bin/forever list
RETVAL=$?
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart)
restart
;;
*)
echo "Usage: {start|stop|status|restart}"
exit 1
;;
esac
exit $RETVAL
When i tried the following command:
/etc/init.d/API start it works fine. When i reboot the system it says "NO forever process" running.

You should have a look at Upstart. People use it with Node. Forever is good just for testing.

I suggest switching to pm2.
$ npm install pm2 -g
$ pm2 start /home/testuser/server.js
$ pm2 list
PM2 can generate and configure a startup script to keep PM2 and your processes alive at every server restart.
$ pm2 startup ubuntu
To save a process list just do:
$ pm2 save
You check here for more information about setting-up pm2 on a Ubuntu server for production.

Related

How to keep a Node JS server running on shared hosting

I was looking to test a node server in a shared hosting environment.
I'm using an ssh terminal session to test.
The server works fine, but of course you can't leave the terminal session without stopping the server.
Using pm2 (npm package), I'm able to keep the server running, but on exiting the terminal session, the pm2 job quits as well, which stops the server. Curious why that would be.
Tried using a crontab to run a shell script that in turn runs the pm2 which in turn starts the node server. The cron tab runs every minute, but the node server never starts.
The sh script works just fine, pm2 works fine, and the node server works fine.
What doesn't work: keeping the node server running after exiting the terminal session.
Here's the shell script that runs the pm2 to trigger the node server...
ps cax | grep node > /dev/null
if [ $? -eq 0 ]; then
echo "Process running."
else
echo "Process not running."
PATH=$PATH:/usr/local/bin
pm2 start '/path/to/NodeServer.js' --restart-delay=100
fi
If someone else like me uses pm2 for godaddy shared hosting, and uses a modified version of Habib's answer with pm2 instead of node, do not forget to include path to node into PATH variable, as it is required by pm2:
PATH=$PATH:/home/user/.nvm/versions/node/v11.15.0/bin
pm2 ps | grep 'my-app'
if [ $? -eq 0 ]; then
echo "Process running."
else
echo "Process not running."
cd /home/user/public_html/app
pm2 start app.js --name my-app
fi
The script above works for me. Specifying only full path to pm2 was not working, as it looks for node, which was not in PATH in the cron environment.
ps cax | grep node > /dev/null
if [ $? -eq 0 ]; then
echo "Process running."
else
echo "Process not running."
/home/user/.nvm/versions/node/v11.15.0/bin/node /home/user/public_html/node/app.js
fi
I used this in cron job in GoDaddy Shared hosting and it is working for me. Before this, I used node /home/user/public_html/node/app.js in the same script but it throws an error because of path of the node. Still, I can use node in the terminal but in cron job, I have to use full path.

Unable to start Node on system reboot Ubuntu Crontab

I have tried this with adding the forever start code in /etc/rc.local didn't work.
When I use the #reboot keyword in /etc/rc.local it says #reboot cannot be found.
So I went back to using crontab Here is my crontab script. All other crontabs are working except the reboot one. In syslog, it says
Jun 4 09:51:12 ip-172-31-28-35 /usr/sbin/irqbalance: Balancing is ineffective on systems with a single cache domain. Shutting down
Jun 4 09:51:12 ip-172-31-28-35 cron[959]: (CRON) STARTUP (fork ok)
Jun 4 09:51:12 ip-172-31-28-35 cron[959]: (CRON) INFO (Running #reboot jobs)
Jun 4 09:51:12 ip-172-31-28-35 CRON[1005]: (ubuntu) CMD (/usr/bin/sudo -u ubuntu /usr/local/bin/forever start home/ubuntu/chat2/index.js)
Which shows that the reboot command in my cron tab is working but for some reason forever is still not starting node. After reboot , I run forever list and it says No forever processes running
I am assuming the problem is somehow with the node and forever paths. I am new to this and dont know which exact path to use on this statement in crontab.
I have also tried the following:
#reboot /usr/local/bin/forever start -c /usr/local/bin/node /home/ubuntu/chat2/index.js
and
#reboot /usr/local/bin/forever start /home/ubuntu/chat2/index.js
None of these are working.
If I run which forever it says
/usr/local/bin/forever
If I run which node it says
/usr/local/bin/node
If I get the full path of my index.js app file, by doing readlink -f index.js in my chat2 directory it says
/home/ubuntu/chat2/index.js
I just want to run this command every time my system reboots. I want to start my node app. The following line works perfect when I cd to the chat2 directory manually. I want this to work on reboot itself.
forever -m5000 -w start index.js
You can create a service with you code instead of using cron. Actually I prefer that because you can stop or start it whenever you want and you can also run it on the system reboot or start.
So:
1- Create a service in /etc/init.d/name_of_file
#!/bin/bash
#/etc/init.d/name_of_file
### BEGIN INIT INFO
# Provides: name
# Required-Start: $syslog
# Required-Stop: $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: add service
# Description:
#
### END INIT INFO
# Some things that run always
case "$1" in
start)
echo "Starting app_name "
touch /var/lock/app_name
cd /where/is/your/file
node index.js &
;;
stop)
echo " Stopping "
rm /var/lock/app_name
sudo pkill -f node
;;
status)
if [ -e /var/lock/app_name ]
then
echo "app_name is running"
else
echo "app_name is not running"
fi
;;
*)
echo "Usage:service app_name{start|stop|status}"
exit 1
;;
esac
exit 0
So after that you have created a service for running you nodejs application.
You have to give running permission to that script
chmod +x /etc/init.d/app_name
Now the only thing you have to do is configure this to run on boot.
Run:
sudo update-rc.d app_name defaults
And then every time you reboot you computer the service will start itself.
Suggest redirect stdout/stderr to file to debug why your script in crontab not work:
/usr/local/bin/forever start -c /usr/local/bin/node /home/ubuntu/chat2/index.js >/tmp/forever.log 2>&1 &
See log file for details after reboot.
You also can try pm2 , like forever but support buildin system start script generate, and will launch your apps after reboot.

"can't cd" within init.d when started as service

I have a very simple script running in init.d to start a node server using forever. It has been working perfectly until recently and i cannot find what can have changed. I am on Debian 7, have not done any update recently.
This is my script (copied from somewhere, and kept simple simple, it is for tests )
#!/bin/sh
#/etc/init.d/nodeup
. /lib/lsb/init-functions
export PATH=$PATH:/usr/local/bin
export NODE_PATH=$NODE_PATH:/usr/local/lib/node_modules
. /home/pat/env
cd /var/www/mydir
FOREVER_ROOT=/var/log/forever/mydir
export FOREVER_ROOT
case "$1" in
start)
exec forever start -m 10 -o $FOREVER_ROOT/output.log -e $FOREVER_ROOT/error.log ./bin/www ./
;;
stop)
exec forever stop ./bin/www
;;
*)
echo "Usage: service nodeup {start|stop}"
exit 1
;;
esac
exit 0
The problem is that when I run (with start or stop, same effect)
sudo service nodeup start
I get
/etc/init.d/nodeup: 12: cd: can't cd to /var/www/mydir
if I run the script with sudo /etc/init.d/nodeup start
it runs perfectly, no problem.
I cannot understand what is going on, or what could have changed on my machine.
Any idea of what I should check that might give now this behaviour ? or what to change in my script so it works again ?
Thanks for any help
I changed the shell of the script from sh to bash
It seems to have rendered the script more stable

pm2 startup doesn't work

I setup my nodejs server successfully and I'm using it on Ubuntu 15.04 server, my issue is that I want my node applications to keep running when the server reboots so I tried pm2, forever and crontab but none of them worked for me, after rebooting I need to start the node application manually.
I tried pm2 as follow:
pm2 startup ubuntu
pm2 start appname
pm2 save
The pm2-init.sh file:
#!/bin/bash
# chkconfig: 2345 98 02
#
# description: PM2 next gen process manager for Node.js
# processname: pm2
#
### BEGIN INIT INFO
# Provides: pm2
# Required-Start: $local_fs $remote_fs
# Required-Stop: $local_fs $remote_fs
# Should-Start: $network
# Should-Stop: $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: PM2 init script
# Description: PM2 is the next gen process manager for Node.js
### END INIT INFO
NAME=pm2
PM2=/home/bashar/.nvm/versions/node/v4.1.1/lib/node_modules/pm2/bin/pm2
USER=bashar
export PATH=/home/bashar/.nvm/versions/node/v4.1.1/bin:$PATH
export PM2_HOME="/home/bashar/.pm2"
get_user_shell() {
local shell=$(getent passwd ${1:-`whoami`} | cut -d: -f7 | sed -e 's/[[:space:]]*$//')
if [[ $shell == *"/sbin/nologin" ]] || [[ $shell == "/bin/false" ]] || [[ -z "$shell" ]];
then
shell="/bin/bash"
fi
echo "$shell"
}
super() {
local shell=$(get_user_shell $USER)
su - $USER -s $shell -c "PATH=$PATH; PM2_HOME=$PM2_HOME $*"
}
start() {
echo "Starting $NAME"
export PM2_HOME
super $PM2 resurrect
}
stop() {
super $PM2 dump
super $PM2 delete all
super $PM2 kill
}
restart() {
echo "Restarting $NAME"
stop
start
}
reload() {
echo "Reloading $NAME"
super $PM2 reload all
}
status() {
echo "Status for $NAME:"
super $PM2 list
RETVAL=$?
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart)
restart
;;
reload)
reload
;;
force-reload)
reload
;;
*)
echo "Usage: {start|stop|status|restart|reload|force-reload}"
exit 1
;;
esac
exit $RETVAL
That didn't work, so I tried to use crontab as follow:
First, I create a script and named it starter.sh
#!/bin/bash
pm2 start /home/bashar/www/node/server.js
Then opened crontab editor:
crontab -e
#reboot /home/bashar/www/node/server.js
Also the above method didn't start my application on the server reboot.
Please advice,
pm2 seems to have a bug during the reboot. After adding pm2 to the automagically starting processes in /etc/init.d, the script works fine under normal processing, but does something weird under a reboot: it wipes the pm2.dump file empty. There are several bug reports like this one, but so far it's still a bug...
The easiest work-around that I've found is as follows:
Edit /etc/init.d/pm2-init.sh, and comment out the line "super $PM2 dump" in the section for stop()
Whenever you modify your pm2 process list, remember to do a manual "pm2 dump"
If anyone has a more permanent solution, please let me know... :)
For anyone who is here looking for Windows machines(as I did), pm2 startup works with unix system only.
https://pm2.keymetrics.io/docs/usage/startup/#init-systems-supported
Try this: https://www.npmjs.com/package/pm2-windows-startup

Supervisord on linux CentOS 7 only works when run with root

I am trying to run a process in the background as a deamon but it only works when I use root as user.
This is what I did.
Installed supervisor as told on their website
$ yum -y install python-setuptools
$ easy_install supervisor
created the config folders
$ mkdir -p /etc/supervisor/conf.d
populate with default settings
$ echo_supervisord_conf > /etc/supervisor/supervisord.conf
add a new user
$ useradd gogopher
on CentOS 7 to make it start automatically I had to do this
$ vim /usr/lib/systemd/system/supervisord.service
added the code below
[Unit]
Description=supervisord - Supervisor process control system for UNIX
Documentation=http://supervisord.org
After=network.target
[Service]
Type=forking
ExecStart=/usr/bin/supervisord -c /etc/supervisor/supervisord.conf
ExecReload=/usr/bin/supervisorctl reload
ExecStop=/usr/bin/supervisorctl shutdown
User=gogopher
[Install]
WantedBy=multi-user.target
now I can enable it so that it starts on reboot. this all works fine.
$ systemctl enable supervisord
$ systemctl start supervisord
$ systemctl status supervisord
OK
editing the config file to include files from conf.d folder
$ vim /etc/supervisor/supervisord.conf
adding at the end of file
[include]
files = /etc/supervisor/conf.d/*.conf
adding a simple program
$ vim /etc/supervisor/conf.d/goapp.conf
[program:main]
command=/srv/www/websiteurl.com/bin/main
autostart=true
autorestart=true
startretries=10
user=gogopher
$ systemctl restart supervisord
no error, but the process does not work
if I reboot nothing happens
$ systemctl status supervisord
shows that it supervisord is running but not the daemon program.
if I run
$ supervisorctl reload
I get the error
error: <class 'socket.error'>, [Errno 111] Connection refused: file: /usr/lib64/python2.7/socket.py line: 571
if I run
$ supervisorctl status main
I get the error
http://localhost:9001 refused connection
I have already disabled selinux.
but the weird part is that if I change both of them to root, it works.
The executable is able to be executed by user group and others.
So I have no idea what is going on. I have heard that I should not use
root as user that is running a webserver for security reasons.
For all the people out there having the same problem, this works for me.
cd
echo_supervisord_conf > /etc/supervisord.conf
# content of /etc/supervisord.conf ...
[supervisorctl]
serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket
[inet_http_server] ; inet (TCP) server disabled by default
port=*:9001 ; (ip_address:port specifier, *:port for all iface) - I had all this wrong from my original config.
username=user
password=passwd
Paste this content into /etc/rc.d/init.d/supervisord ( I´m not the owner of this script, by now i don´t remember where i got it from )
#!/bin/sh
#
# /etc/rc.d/init.d/supervisord
#
# Supervisor is a client/server system that
# allows its users to monitor and control a
# number of processes on UNIX-like operating
# systems.
#
# chkconfig: - 64 36
# description: Supervisor Server
# processname: supervisord
# Source init functions
. /etc/rc.d/init.d/functions
prog="supervisord"
prefix="/usr/local/"
exec_prefix="${prefix}"
prog_bin="${exec_prefix}/bin/supervisord -c /etc/supervisord.conf"
PIDFILE="/var/run/$prog.pid"
start()
{
echo -n $"Starting $prog: "
daemon $prog_bin --pidfile $PIDFILE
sleep 1
[ -f $PIDFILE ] && success $"$prog startup" || failure $"$prog startup"
echo
}
stop()
{
echo -n $"Shutting down $prog: "
[ -f $PIDFILE ] && sleep 1 && killproc $prog || success $"$prog shutdown"
echo
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status $prog
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
;;
esac
Make the script executable and register it as a service
sudo chmod +x /etc/rc.d/init.d/supervisord
sudo chkconfig --add supervisord
sudo chkconfig supervisord on
# Start the service
sudo service supervisord start
# Stop the service
sudo service supervisord stop
# Restart the service
sudo service supervisord restart

Resources