PM2 – a task runner for Node.js

PM2 is a production-process manager that helps to scale the Node.js up or down, as well as load balance the instances of the server. It also ensures that the processes are running constantly, tackling down one of the side effects of the thread model of Node.js: an uncaught exception kills the thread, which in turn kills your application.

Single-threaded applications and exceptions

As you learned before, Node.js applications are run in a single thread. This doesn't mean that Node.js is not concurrent, it only means that your application runs on a single thread, but everything else runs parallel.

This has an implication: if an exception bubbles out without being handled, your application dies.

The solution for this is making an intensive use of promises libraries such as bluebird; it adds handlers for success and failures so that if there is an error, the exception does not bubble out, killing your app.

However, there are some situations that we can't control, we call them unrecoverable errors or bugs. Eventually, your application will die due to a badly handled error. In languages such as Java, an exception is not a huge deal: the thread dies, but the application continues working.

In Node.js, it is a big problem. This problem was solved in the first instance using task runners such as forever.

Both of them are task runners that, when your application exits for some reason, rerun it again so it ensures the uptime.

Consider the following example:

Single-threaded applications and exceptions

The helloWorld.js application is now handled by forever, which will rerun it if the application dies. Let's kill it, as shown in the following image:

Single-threaded applications and exceptions

As you can see, forever has spawned a different process with the 4903 PID. Now, we issue a kill command (kill -9 4093) and that is the output from forever, as follows:

Single-threaded applications and exceptions

Although we have killed it, our application was respawned by forever without any downtime (at least, noticeable downtime).

As you can see, forever is pretty basic: it reruns the application as many times as it gets killed.

There is another package called nodemon, which is one of the most useful tools for developing Node.js applications. It reloads the application if it detects changes in the files that it monitors (by default, *.*):

Single-threaded applications and exceptions

Now, if we modify the helloWorld.js file, we can see how nodemon reloads the application. This is very interesting in order to avoid the edit/reload cycle and speed up the development.

Using PM2 – the industry-standard task runner

Although, forever looks very interesting, PM2 is a more advanced task runner than forever. With PM2, you can completely manage your application life cycle without any downtime, as well as scale your application up or down with a simple command.

PM2 also acts as a load balancer.

Let's consider the following example:

var http = require('http');

var server = http.createServer(function (request, response) {
  console.log('called!');
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World
");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");

This is a fairly simple application. Let's run it using PM2:

pm2 start helloWorld.js

This produces an output similar to the following image:

Using PM2 – the industry-standard task runner

PM2 has registered an app named helloWorld. This app is running in the fork mode (that means, PM2 is not acting as a load balancer, it has just forked the app) and the PID of the operating system is 6858.

Now, as the following screen suggests, we will run pm2 show 0, which shows the information relevant to the app with id 0, as shown in the following image:

Using PM2 – the industry-standard task runner

With two commands, we have managed to run a simple application in a very sophisticated way.

From now on, PM2 will ensure that your app is always running so that if your application dies, PM2 will restart it again.

We can also monitor the number of apps PM2 is running:

pm2 monit

This shows the following output:

Using PM2 – the industry-standard task runner

This is the PM2 monitor. In this case, it is a complete overkill as our system is only composed of one application, which runs in the fork mode.

We can also see the logs executing pm2 logs as shown in the following image:

Using PM2 – the industry-standard task runner

As you can see, PM2 feels solid. With few commands, we have covered 90% of the monitoring necessities of our application. However, this is not everything.

PM2 also comes with an easy way to reload your applications without downtime:

pm2 reload all

This command ensures that your apps are restarted with zero downtime. PM2 will queue the incoming requests for you and reprocess them once your app is responsive again. There is a more fine-grained option where you can specify reloading only certain apps by specifying the app name:

pm2 reload helloWorld

For those who have been fighting for years with Apache, NGINX, PHP-FPM, and so on, this will sound very familiar.

Another interesting feature in PM2 is running your application in the cluster mode. In this mode, PM2 spawns a controller process and as many workers (your app) as you specify so that you can take the benefit of multicore CPUs with a single-thread technology such as Node.js.

Before doing this, we need to stop our running application:

pm2 stop all

This will result in the following output:

Using PM2 – the industry-standard task runner

PM2 remembers the apps that were running, so before rerunning the app in the cluster mode, we need to inform PM2 to forget about your app, as follows:

pm2 delete all
Using PM2 – the industry-standard task runner

We are ready to run our app in the cluster mode:

pm2 start helloWorld.js -i 3
Using PM2 – the industry-standard task runner

PM2 is acting as a round-robin between the main process and the three workers so that they can cope with three requests at the same time. We can also scale down or up our number of workers:

pm2 scale helloWorld 2

This will result in two processes being run for the same app instead of three:

Using PM2 – the industry-standard task runner

As you can see, with very little effort, we have managed to configure our app in order to be production ready.

Now, we can save the status of PM2 so that if we restart the server, and PM2 is running as a daemon, the apps will automatically start.

PM2 has a code API so that we can write a Node.js program to manage all the steps that we have been manually doing. It also has a way of configuring your services with a JSON file. We will discuss this in more depth in Chapter 6, Testing and Documenting Node.js Microservices, when we study how to use PM2 and Docker to deploy Node.js applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.77.63