Deploying Node.js production. Part 1: Using pm2.

Once the development is complete - you are ready to share your application or with the world. Here comes the question: how exactly do you deploy it? Obviously, you can't just run "node main.js" and leave it like that. If the application crashes due to untested error or out of memory, you don't want your service to be interrupted. Instead the applicatoin should be automatically restarted, giving you some extra time to investigate the issues. NOTE: have you completed my other tutorials about building Node.js web chat and web game? They are a great example of a typical node.js apps and you can use them to test your production deployments! Try to run your web chat with PM2! There are multiple ways to achieve more fault-tolerant setup. One way could be to "dockerise" your applicatoin and let tools like Kubernetes monitor Docker container. However this approach tends to be viable only for fairly large-scale deployments. For smaller applicatoins it will be a big overhead. In this article I'll show a much lighter approach to management and monitoring of Node apps using a tool called PM2. PM2 acts as a watchdog: if node.js process dies or exceeds certain memory threshold, pm2 will restart it. Moreover, pm2 presents a nice overview of your running processess and alows to start multiple related node.js applications with just one command. Without further ado, let's install pm2 to the system:
  1. > npm install -g pm2
Once it is installed, let's start our node.js applicatoin "pm2 way":
  1. > pm2 start main.js
Now pm2 manages the app. What happens if the app crashes? Let's see. If you're on windows, go to task manager and kill the node.js process, on linux command line you can do following:
  1. > ps aux | grep node
To find the PID of running process. Then just run
  1. > kill -9 [PID]
Replace [PID] with the ID of running node process and check out if the application is still running. You'll see that the app is there as if it wasn't ever killed! What happened? PM2 restarted the application, because it noticed that the process is dead. There are few other useful commands that you should try with PM2:
  1. > pm2 status
This command will list the currently running applications an their state.
  1. > pm2 logs
As the name implies, it will output the logs of running apps. Finally, if you want to stop and "remove" application from PM2, you can run the following:
  1. > pm2 stop appname
  2. > pm2 delete appname
PM2 is a much better way way to manage your node.js applciations than just running them in console. There are many services that are using pm2 in production to run, monitor and diagnose their node.js applications. Read more about pm2 here: http://pm2.keymetrics.io/

Tags

Add new comment