Keeping Node.js applications running using Forever

Introduction

You ever had to restart your Node.js instances manually since it was crashed?

Well, I had. And maybe right now you are being stuck in the middle of the situation.

Server gets OOM (Out-of-Memory), it automatically kills Node.js. Runtime exceptions is very likely to kill your application, too.

Worst case, supposed it was in the middle of the night, 3AM for example, when you were continuously getting service-down notifications in your dreams. You’d wish, ‘Hope it could somehow automatically restart for me‘.

Using Forever to keep your app running

As its name describes, forever, will keep your Node.js apps running continuously as a service and it will automatically handle unexpected crashes for you.

Apart from automating the recovery tasks, it will start your server in the child process but a long running process so that your server will still living even though you close the Terminal/ Shell window.

Installing and start daemonizing

  1. You could install forever globally using npm:
  2. After installing, you can now run your node.js application by typing:
    But note that this will take you into a long running process, it will exit when you close the Terminal or terminate when you press Ctrl + C.

    In order to prevent this, we should run the application as a background service, by adding start into the command:

    forever restarts your application whenever it stops for whatever the reasons are. To limit the amount of times it restarts, use: -mX. 6 times for example:

  3. To list all running applications:

    You will find something like this:

    The number in the [] brackets is used for users (you) to take manual actions in forever.

  4. Stop a process by:

    is the process id we took from the #3.

  5. To restart a running application, goes:

  6. If you are developing some scripts, use -w for automatic restarts when the file changes:

Conclusion

Right now forever only supports Node.js applications. Maybe it will support other services like PHP or MySQL in the future, who knows?

But at this moment, we can tell that it can help keeping my & your Node.js server up and take away a lot of headaches.