Compute Engine and NodeJS, keep online

I have a website already developed with node.js and sails.js on "Compute Engine" but to start it, necessarily I have to write "node app.js" in the SSH console of browser. But there is a problem (since I am new to Linux and Google Cloud :)), if I want my Node app it keep online, the SSH window must be open, if I close, the Node application will terminate, like Ctrl+c. So it makes no sense to have my computer turned on, just to have the active window. So, how to keep my NodeJS app online without being in the presence of SSH console?. I know the question is illogic to some, but I would appreciate if you help me. Thanks

Upvotes: 2

Views: 2347

Answers (3)

Jongho Lee
Jongho Lee

Reputation: 101

You can install forever module (https://www.npmjs.com/package/forever) to your Google compute engine using SSH window.

npm install forever -g

Then, in your node server directory, execute your server using forever.

forever start [YOUR_SERVER_FILE.js]

Now, if you close the SSH window, your node server is still on !!

Good luck!

Upvotes: 3

Soufiane Sakhi
Soufiane Sakhi

Reputation: 1

The best solution would be using a module called forever: https://www.npmjs.com/package/forever

You can use it this way: forever start your_script.js

Upvotes: 0

José F. Romaniello
José F. Romaniello

Reputation: 14156

First of all it is not related to Compute Engine nor Node.js.

You mention that the application will terminate if you press ctrl+c and that's correct because you are running your application in the foreground instead of background. To run your application in the background you can either launch your app like this:

node app.js &

Or you can launch with node app.js and then press ctrl+z.

But just sending the application to the background wouldn't help. As soon as you disconnect from your ssh session, all programs started (background or foreground) will receive a HUP signal, in node.js you can handle that signal but the default behaviour is to close:

On non-Windows platforms, the default behaviour of SIGHUP is to terminate node

One thing that you can do to ignore the SIGHUP signal is running your app as follows:

nohup node app.js &

If you do this, your application will continue to run even when you close your ssh session. Another way to achieve this is by using the screen.

This will help you on very early stage and for development but I don't recommend using neither of these things for production. Eg: if your application crash it should be restarted. The recommended way is to use a service manager that comes with the OS: upstart, systemd, init, to name a few.

Upvotes: 7

Related Questions