How to Keep Node.js Running at Linux Server

2014/08/023 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Using Respawn
  3. Using nohup with Respawn
  4. Conclusion

Introduction

This article explains how to use the respawn npm module together with nohup to keep a Node.js application running on a Linux server.

Using Respawn

nohup node respawn.js &

There's a good article about how to use respawn: http://java.dzone.com/articles/how-keep-nodejs-processes.

  • respawn GitHub

  • respawn npm module

How to use respawn:

  1. Create a file with any name. The code can be referenced from https://github.com/mafintosh/respawn
  2. Type node [your file name containing respawn code].js

After you finish this, your site will not go down. For example, if your /failUrl has a syntax error and you start with node server.js, your Node.js app will go down. However, with respawn, /failUrl will show as down, but the page will load successfully when you go to the home page /.

Using nohup with Respawn

Respawn is great, simple, and easy to use. However, it didn't work for me because I'm using the command line to log in to my Linux box. So if I close my command line window, the thread is gone. I need to let respawn run in the background, and that's what nohup does.

The forever npm module does the same thing. However, if you know nohup, you have another option. I had an experience where one day my Node.js web application didn't work, and typing npm install forever resulted in lots of errors and took a long time to figure out what was going on. But with nohup and respawn, it's easy.

Simply change the last step to the following:

nohup node respawn.js &

After closing your remote console window, your Linux Node.js server will still be working fine.

*Node.js/Express.js is great for Web API’s and applications. In contrast to known enterprise technologies, Node.js is very special. It’s a single process/threaded environment. If an unhanded exception occurs, the Node.js virtual machine simply stops, leaving the application in an unresponsive state.

Due to the async nature of Node.js, try/catch doesn't always work, even with domains and stuff you have a chance that the application crashes on production while you sleep.

from http://java.dzone.com/articles/how-keep-nodejs-processes.\*

This is Node.js — it's different.

Conclusion

Using respawn with nohup is a simple and effective way to keep your Node.js application running on a Linux server. Respawn automatically restarts your application if it crashes, and nohup ensures the process continues running even after you close your terminal session.