3

I've created a simple NodeJS app which I have now moved up to a server in AWS.

I'm able to ssh into the server and start the application but obviously as soon as I close the terminal the process stops.

How to I start my NodeJS app and keep it running after I've closed my terminal?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
michael
  • 4,427
  • 6
  • 38
  • 57

2 Answers2

5

That's not a specific nodejs problem, although there are specific solutions (for example forever).

A generic solution to remotely start any program on linux and not have it die when you close the session is to launch it using nohup. Here's an example in which I launch node and redirect both the standard and error outputs into the server.log file :

nohup node main.js >> server.log 2>&1 < /dev/null & 
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
4

Like Denys Seguret said, this can be done using the forever node package. Here's how -

SSH into your server and install forever globally as root level user

sudo npm install forever --global

To run forever on a a node script, execute in terminal while in same directory as your server.js like this -

forever start server.js

Make sure to test if its working by launching your browser at the appropriate url. If you want to check the status of all of the forever scripts you have running on your server (you can run it on multiple scripts) run this command -

forever list

and to stop a forever script you can either run forever stop which will stop all your forever scripts I believe, or run forever stop 0 where 0 is the index of your script in the forever list.

I use forever on all my gulp applications, haven't had any problems yet, but I don't think I have had any major shut down issues with my remote server. Maybe if that happens I'll have more to say about the credibility of forever. Some credits for this answer from this website.

kiko carisse
  • 1,634
  • 19
  • 21