By the end of this chapter, you should be able to:
In the Express.js documentation Performance Best Practices section, which we highly recommend looking over in general, there is a section called "Ensure your app automatically restarts", the documentation suggests that you utilize a process manager:
In development, you started your app simply from the command line with node server.js or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a “container” for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime.
Basically, the built-in
node app.js pattern, or even
nodemon app.js, are not suitable scripts for running your app in production mode.
There are three popular process managers for Node.js:
The most popular process managers for Node are as follows:
We are going to make use of pm2 for its ease of setup and powerful features.
You must install PM2 in the containing environment where you'll run the app. This might be a Docker container, a virtual machine, a remote server, etc... but in this tutorial, we will install it on our machines.
As with nodemon, which we used for restarting the development server on file change (by the way, pm2 has a development mode that does the same thing), we can install the package globally like so:
npm install [email protected] -g
Next, we can run our app immediately just by invoking a simple command:
pm2 start app.js
That's it! PM2 will automatically restart your app if it crashes (a certain number of times... if it crashes too many times in a row it will abort).
However, we haven't taken advantage of all the features yet...
A great advantage of using PM2 for production is that it has a built-in ability to run your app in cluster-mode. From the Express documentation:
In a multi-core system, you can increase the performance of a Node app by many times by launching a cluster of processes. A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances.
Let's re-run our app in cluster mode:
pm2 start app.js -i max
There you have it! We just add a simple
-i max flag to run on the maximum amount of CPU cores -- if you're on a MacBook, it's probably either 2 or 4. Now we have several instances of our server that are going to share the load. Best of all, we didn't have to write any code for this feature!
.yml) configuration file, and have the script reference that. Both the quickstart and the full documentation for PM2 are great at explaining this already, so go check them out.
When you're ready, move on to Introduction to Heroku