Auto start node.js application on linux server

So we are developing node.js application and we want to keep it runing on server

What we need?

  1. node.js application auto start on linux server boot
  2. node.js application auto restart when it crashed
  3. node.js application auto restart when files change
  4. developer can check the output of node.js application anytime

Easy problem first

The problem 2,3 are easily solved by the nodemon module. This module can auto restart node.js app when it crashed and also when files of the app changed. OK, let’s install it and get it running first:

npm install -g nodemon
cd /path/to/app
nodemon app.js

And we see the outputs of the app, and also we have auto restart feature now.

OK, if we close our terminal (for me, it’s putty), the nodemon process will be termiated as its parent process termiated. so let’s introduce screen to keep the session. to use it:

screen -S nodeapp

And now we are in the new screen session (whose name is nodeapp). run the nodemon command:

nodemon app.js

Now we can press Ctrl+A,D to detach the screen session, and even we close putty, the node is still runing. and later, when we login to the server again,and use:

screen -r nodeapp

to attach into the screen session again.

so we solved problem 2,3,4 now

we make this into a shell script so we can run it anytime

touch ~/nodeapp.sh
chmod u+x ~/nodeapp.sh

add add following shell command into it

#!/bin/bash
cd /home/william
nodemon /path/to/app.js

Auto start on server boot

Next, let’s focus on problem 1. to auto start the node app when server boot, in our situation, we want the server to automaticlly create a screen session, and start nodemon in it.

When search on internet, i found many different solution for this, some one suggest systemd, upstart, and Monit etc.

But consider diffirent linux distro have diffirent boot machanism, it’s a little bit hard to do that.

My solution is a lot easier. and much flexiable. We want:

it auto start a screen session so that the developer can attach to that screen session again to see the outputs.

In most linux distro, we can find the /etc/init.d/rc.local file. this file is designed to be a custom shell script which will run on everytime the server boot. And in most case, that file will source the /etc/rc.local file too, so let’s add our command there.

the command to add is:

su - william -c 'screen -d -m -S nodeapp /home/william/nodeapp.sh'

Let me explain this command, we can split it into 3 parts:

  1. su - william: this command switch into the william user who is the developer of the node.js app
  2. -c '....': this part run the xxxx command once it logged into the developer user
  3. screen -d -m -S nodeapp /home/william/nodeapp.sh: this part start a deattached screen session whose name is nodeapp and run the nodeapp.sh shell script