Keep Your NodeJS App Alive With AWS EC2 & PM2
Let’s walkthrough one of many options for managing your NodeJS production processes
Quick Note:
This post can be used as a continuation of Deploying a NodeJS Application With AWS EC2, SSL, and a Load Balancer — Where I walked through the basics of getting a NodeJS application up and running EC2 and an application load balancer.
From the previous post, we have a small NodeJS application created on an EC2 instance; after installing node and express on the server and creating a index.js
file to handle a couple of requests, I can run the server like so:
[ec2-user@ip-172-31-19-125 test-node-app]$ node index.js
Example app listening on port 8080
However, I don’t want my local computer to be in charge of managing the running process. What happens when I close my terminal or if my computer shuts down? Of course, I will lose my application process.
Enter: PM2
PM2 is a process management tool that runs on a daemon to keep your application running in the background 24/7 — To get your application up and running with PM2 is very straightforward; let’s walk through that now.
Once you have an EC2 instance running, SSH into the server, and run the following commands:
$ npm install pm2@latest -g$ pm2 start index.js
You will see an output explaining what PM2 is and a few helpful commands:
Helpful Commands:
$ pm2 list
— List all the running applications
$ pm2 show [name]
— Display metadata for a specific process
$ pm2 monit
— Monitor the resource usage of your application
$ pm2 stop [name]
— Stop a specified application
$ pm2 delete [name]
— To stop and delete an application
Now you’ll be able to access your NodeJS application 24/7! This walkthrough scratches the surface of PM2 and all of the capabilities it provides. You will likely want to build out a complete build.sh
script that handles a more sophisticated PM2 start-up process but this work for us now. I will continue to post more information as my application develops and the requirements become more complex.
Alternatives to PM2 worth checking out:
Passenger — This service is an app server that efficiently runs and auto-manages your web apps. It also improves security, reliability, and scalability.
Systemd — This service offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points, and implements an elaborate transactional dependency-based service control logic.
Forever — A simple CLI tool ensuring that a given script runs continuously (i.e., forever). Note that this project currently entirely depends on the community to implement fixes and new features.