How to keep a Node JS server running on shared hosting

Viewed 1330

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
2 Answers

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.

Related