user285594
user285594

Reputation:

BASH - why my NodeJS server script crashing?

Running CentOS (Linux signal-server 3.10.0-123.8.1.el7.x86_64). When i login to the server using SSH and then execute this following line manually it works, but crash when i exit my SSH connection to the server.

$ node /var/www/html/signal-server/avi.js &

This robot also fails to let the server run when i am not manually logged in via SSH:

#!/bin/bash
while :
do
  # 1
  avi=$(pgrep -f "avi.js")
  if [[ "$avi" ]]; then
    log1="1 - running avi.js $1 $2"
  else
    log1="1 - re-launch avi.js $1 $2"
    ps aux | grep "avi.js" | awk '{print $2}' | xargs kill
    sleep 1
    # same if nohup also used
    node /var/www/html/signal-server/avi.js &

  fi

  tt=$(date +"%Y-%m-%d %T")
  echo "$tt" "$log1"

  sleep 2
done

How can i make it run for-ever please? (i have also other services they are working fine only this one always crashing when i logout from the SSH session)

Upvotes: 0

Views: 129

Answers (1)

Leon
Leon

Reputation: 12481

nohup will do what you want

nohup node /var/www/html/signal-server/avi.js &

You should really write a systemd script for you service, then if your server restarts your service will startup again.

This is a rough idea what such a script may look like

[Service]
ExecStart=node /var/www/html/signal-server/avi.js
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=node-avi
User=some-user
Group=some-group
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target

Spend a bit of time reading the systemd documentation

Upvotes: 2

Related Questions