1

I have a NodeJS server on a virtual machine. I connect to the machine through SSH and leave the server running with:

npm start &

If I disconnect with Ctl-D, the server keeps running. If my internet drops and the connection fails, the server also stops. Why does this happen, and how can I leave the server running without it dropping because of the internet disconnection?

1

Even when it is running in the background, the server is still a child process of your ssh session. To get it to run independently, you can run it with nohup:

nohup npm start &

Wikipedia says:

Note that nohupping backgrounded jobs is typically used to avoid terminating them when logging off from a remote SSH session. A different issue that often arises in this situation is that ssh is refusing to log off ("hangs"), since it refuses to lose any data from/to the background job(s). This problem can also be overcome by redirecting all three I/O streams:

nohup npm start > npm.out 2> npm.err < /dev/null &
7
  • I ran NODE_OPTIONS=--max_old_space_size=50000 NODE_ENV=production nohup npm start >> stdout5.md 2>> stderr5.md < /dev/null &, the SSH session disconnected because of an internet failure, and the server went down. How can I debug it? Aug 31 '21 at 18:59
  • 1
    Can you close the ssh session manual (ctrl-d) just after starting the server and have it stay up? Aug 31 '21 at 19:08
  • 1
    You could also try configuring npm as a system service: serverfault.com/questions/1018676/… Aug 31 '21 at 19:09
  • 1
    I'm not sure if it would help, but I usually configure my SSH client to detect timeouts and reconnect: $ cat ~/.ssh/config ConnectTimeout 10 ConnectionAttempts 100 you could also try using a keep alive ping with ServerAliveInterval 60. Those might reduce the problem. Sep 1 '21 at 10:18
  • 1
    I'm a bit surprised that you still have this problem when using nohup. If that isn't working for you, my only other suggestion is configuring npm as a service. Sep 1 '21 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.