What is PM2 and how to use it?
Introduction
Managing and running Node.js without interruption can be challenging; that’s where PM2 comes in. PM2 excels as a premier process manager for Node.js applications that helps you start, stop, and restart your app if it crashes. The tool is designed to simplify the deployment, management, and monitoring of Node.js apps. This guide outlines a step-by-step process for installing PM2, key advantages, and a usage walkthrough for Node.js on an AWS EC2 instance.
What is PM2?
PM2 is a popular process manager for Node.js applications. It helps programmers manage, monitor, and keep Node.js processes running in the background, especially in the case of the production environment. It is a handy tool that guarantees smooth operation, effective handling of multiple applications, centralized logging, load balancing, and a resilient ecosystem.
Key Features of PM2
Process Management
It lets you start, stop, restart, and delete processes easily, and also enables you to manage multiple apps simultaneously.
Load Balancing
The built-in load balancing feature distributes incoming traffic across multiple instances of an application, improving scalability and performance.
Logging and Monitoring
PM2 offers logging and monitoring tools to view logs, monitor CPU and memory usage, and performance metrics, helping you track and debug issues.
Automatic Restart
The feature enables restarting apps when they crash or encounter any failure, ensuring uninterrupted service and reducing disruption for the end user.
Startup Scripts
This PM2 feature generates startup scripts to ensure the app automatically restarts on server reboots.
Configuration Files
PM2 supports ecosystem.config.js (preferred), JSON, or YAML files for managing application settings.
Why use PM2?
PM2 is widely used in production environments because it simplifies the management of Node.js applications. Here is why developers use PM2:
- PM2 can automatically restart your application if it crashes and automatically reload your application when you update your code.
- PM2 enables easy monitoring and works like a health tracker for your node app. It shows memory usage states and more in a centralized dashboard.
- PM2 allows you to manage multiple Node.js applications on the same server, and it provides a convenient CLI interface for starting, stopping, and monitoring your applications.
- PM2 can aggregate the logs from your Node.js applications into a single location, making it easier to manage and analyze your logs.
- PM2 can distribute incoming requests across multiple instances of your Node.js application, allowing you to handle more traffic and improve the performance and reliability of your application.
- PM2 has a large and active community, and it integrates with many popular tools and frameworks, making it a versatile and reliable choice for managing Node.js applications.
Overall, PM2 can help you streamline the deployment and management of your Node.js applications, improve their performance and reliability, and simplify your development workflow.
How to Install PM2 with Node on AWS EC2?
To install PM2 with Node.js on an AWS EC2 instance, follow these steps. Note that instructions vary depending on the EC2 instance’s operating system (e.g., Amazon Linux or Ubuntu).
Step 1: Connect to Your EC2 Instance
Use SSH to connect to your EC2 instance. The default user depends on the OS:
- Amazon Linux: ec2-user
- Ubuntu: ubuntu
Example for Amazon Linux:
ssh -i your-key.pem ec2-user@your-ec2-instance
Replace your-key.pem with your key file and your-ec2-instance with the instance’s public IP or DNS.
Step 2: Install Node.js and npm
Install a current Long-Term Support (LTS) version of Node.js (e.g., Node.js 20). Instructions vary by OS.
For Amazon Linux 2 or Amazon Linux 2023:
sudo yum update -y
curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
sudo yum install -y nodejs
For Ubuntu:
sudo apt-get update
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
Verify the installation:
node -v
npm -v
Step 3: Install PM2
Install PM2 globally using npm:
sudo npm install pm2 -g
Verify the installation:
pm2 -v
Step 4: Start Your Node.js Application
Navigate to your application directory and start your Node.js app with PM2:
cd /path/to/your/app
pm2 start app.js
Replace app.js with your main application file.
To enable load balancing with cluster mode:
pm2 start app.js -i max
This runs multiple instances based on available CPU cores.
Step 5: Set Up Automatic Startup
Ensure your application restarts after server reboots:
pm2 startup
Copy and run the generated command to configure startup scripts.
Step 6: Save the Process List
Save the current PM2 process list to persist across reboots:
pm2 save
Your Node.js application is now managed by PM2 on your EC2 instance.
Security Note
- Run PM2 as a non-root user (e.g., ec2-user or ubuntu) to minimize security risks.
- Configure AWS Security Groups to allow only necessary ports (e.g., 80 for HTTP, 443 for HTTPS, 22 for SSH).
- Secure your SSH key file (your-key.pem) and rotate it periodically.
How to List All Processes in PM2
To list all the processes inside the PM2 manager, you can use the following command:
pm2 list
This command will display a table containing information about all the processes currently managed by PM2, including the process name, process ID (PID), status, and other details.
- If you have many processes and want to filter the results based on a specific criterion, you can use the --sort and --filter options. For example, to list all the running processes sorted by memory usage, you can use the following command:
pm2 list --sort memory
- To list all the processes with "app" in their name, you can use the following command:
pm2 list --filter app
These options help you quickly find the necessary information and manage your processes more efficiently with PM2.
Common PM2 Commands
The table below showcases some basic PM2 commands that will easily help you manage Node.js apps.
Command | Description |
---|---|
pm2 start app.js | Start an application |
pm2 list | List all managed processes |
pm2 stop app_name | Stop a running app by name or ID |
pm2 restart app_name | Restart a running app |
pm2 delete app_name | Stop and remove an app |
pm2 logs | Display logs for all apps |
pm2 monit | Monitor processes via a dashboard |
pm2 save | Save the current process list |
Using PM2 with Non-Node.js Applications
While PM2 is designed for Node.js, it can manage other processes using custom interpreters. For example, to run a Python script:
pm2 start script.py --interpreter python3
Configuration with Ecosystem Files
For advanced setups, use an ecosystem.config.js file to manage multiple applications and settings. Example:
module.exports = {
apps: [
{
name: 'my-app',
script: 'app.js',
instances: 'max',
exec_mode: 'cluster',
Conclusion
Discover the power of PM2 for Node.js applications – from automatic restarts and code reloads to managing multiple applications, centralized logging, load balancing, and integration with popular tools. Follow the guide to install PM2 on AWS EC2, streamline deployment, and enhance the performance, reliability, and development workflow of your Node.js applications.
Hire Node.js developers with us to launch your app with minimal downtime. Our Node.js experts keep up with the latest advancements and follow best practices to build secure, scalable, and advanced solutions for your needs.