How do I leave Node.js server on EC2 running forever?

Sprout Coder picture Sprout Coder · Oct 7, 2014 · Viewed 41.3k times · Source

As you can tell by my question, I'm new to this...

I built my first website, I set up my first Node.js server to serve it and then pushed everything live on EC2.

I tested everything on my EC2 IP address and everything seems to be working.

Now up until now, I've been testing my app locally so it makes sense that whenever I closed the terminal, app.js would stop running so nothing would be served on localhost.

Now that my server is on EC2, the same thing happens ("obviously" one could say..) whenever I close my terminal.

So my question is how do I keep my Node.js server running on EC2 for like... forever..so that my site stays live.. forever :)

I read something about a node module called "forever" but I'm wondering (being new and all..) why isn't this "forever" functionality a default setting of the Node.js-EC2 system ?

I mean, correct me if I'm wrong, but isn't the whole point of setting up a web server and pushing it live to have it stay live forever? Isn't that what servers are supposed to do anyway (infinitely listening for requests) ? And if that's the case why do we need extra modules/settings to achieve that ?

Thanks for your help.. As you can tell I'm not only looking for a solution but an explanation as well because I got really confused.. :-)

EDIT (a few details you might need) - After installing my app on EC2 these are the steps that I follow on the terminal (The app is running on Amazon Linux by the way) :

  • I type ssh -i xxxxxxxxxxx.pem [email protected] on the terminal

  • After logging onto the Amazon machine I then go to the relevant folder and execute node app.js

  • There are 3 folders in the machine : node, node_modules and *name of my app*

  • app.js resides in *name of my app*

  • After that, the site goes live on my EC2 IP

  • Once I close the terminal, everything is switched off

Answer

James Wilson picture James Wilson · Oct 8, 2014

Before you invoke Node.js, run the command:

screen

This will create a persistent environment which will allow your process to keep running after you disconnect.

When you reconnect, you can use this command to reconnect to that environment:

screen -r

Here's a random link to learn more about screen:

http://www.rackaid.com/blog/linux-screen-tutorial-and-how-to/

However, this won't help you if your EC2 instance restarts. There are many different ways to do that. Adding your startup command to /etc/rc.local is one way. Here's a link to an Amazon guide which includes adding something to /etc/rc.local.

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/building-shared-amis.html

Hope this helps,

James