Auto start NodeJS project on system boot:

Assuming your codebase is in /www/ps-api

vim /etc/crontab:

@reboot root bash /www/ps-api/_cron/

vim /www/ps-api/_cron/

# start app
iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 1080
iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 1443
ufw allow 80/tcp
ufw allow 443/tcp

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/gitlab
cd /www/ps-api
git reset HEAD -\-hard;
git pull

#while true; do
#    i=$[$i+1]
#    echo node api.js \#$i
#    node api.js
#    sleep 5

pm2 start api.js

vim /www/ps-api/api.js

// This is your Node.js codebase

every time the server boots up, it will execute "", which will serve "api.js".

Multiple ways of actually running the "api.js" Node.js script.

  • First of all, you can do just "node api.js", but that is unreliable - if the script has a fatal error, it will crash and exit the process. Then, your server will not be running anything - and you will no longer have a website running.
  • Or, you can run "node api.js" inside a loop - so if the process crashes, it is immediately restarted.
  • Or, you can use a process manager to spawn the node process. PM2 is a great system-level script, which can monitor your node.js script, restart it if necessary, restart if it starts taking too much memory, run multiple scripts at the same time, etc.

results matching ""

    No results matching ""