How to Use Pm2 for Nodejs
Introduction PM2 is a powerful process manager for Node.js applications that simplifies deployment, monitoring, and management. As Node.js applications often need to run continuously in production environments, PM2 ensures your apps stay alive, restarts them on failure, and provides tools for load balancing and log management. Understanding how to use PM2 effectively can greatly improve your devel
Introduction
PM2 is a powerful process manager for Node.js applications that simplifies deployment, monitoring, and management. As Node.js applications often need to run continuously in production environments, PM2 ensures your apps stay alive, restarts them on failure, and provides tools for load balancing and log management. Understanding how to use PM2 effectively can greatly improve your development workflow, increase application reliability, and streamline server management.
This tutorial provides a comprehensive guide on how to use PM2 with Node.js, covering installation, configuration, process management, and best practices. Whether you are a developer, system administrator, or DevOps engineer, mastering PM2 will help you maintain robust Node.js applications in production.
Step-by-Step Guide
1. Installing PM2
To get started, you first need to install PM2 globally using npm:
npm install pm2 -g
This command installs PM2 globally, allowing you to manage Node.js processes from anywhere in your terminal.
2. Starting a Node.js Application with PM2
Once installed, you can start your Node.js app using PM2. For example, if your app entry point is app.js, run:
pm2 start app.js
This launches your application and assigns it a process ID for management.
3. Listing Running Processes
To view all running processes managed by PM2, use:
pm2 list
This command shows the status, CPU usage, memory consumption, and uptime of each process.
4. Monitoring Application Logs
PM2 collects logs for your applications. To view real-time logs, run:
pm2 logs
You can also view logs for a specific app by specifying its name or process ID:
pm2 logs <app_name_or_id>
5. Restarting Applications
To restart an app (e.g., after code changes), use:
pm2 restart <app_name_or_id>
This reloads the app without downtime when used with cluster mode.
6. Stopping and Deleting Processes
To stop an app:
pm2 stop <app_name_or_id>
To remove it from PM2's process list:
pm2 delete <app_name_or_id>
7. Auto Startup on Server Boot
To ensure your Node.js apps managed by PM2 restart automatically after a server reboot, generate and configure a startup script:
pm2 startup
Follow the instructions output by the command, which usually involves running a system command with elevated privileges.
After setting up, save your current process list:
pm2 save
8. Using Ecosystem Files for Configuration
For complex deployments, use an ecosystem file (ecosystem.config.js) to define multiple apps, environment variables, and deployment settings. Example:
module.exports = {
apps: [{
name: "my-app",
script: "./app.js",
instances: 2,
exec_mode: "cluster",
env: {
NODE_ENV: "development"
},
env_production: {
NODE_ENV: "production"
}
}]
}
Start apps defined in the ecosystem file with:
pm2 start ecosystem.config.js
9. Reloading Applications Without Downtime
To reload an app in cluster mode without downtime:
pm2 reload <app_name_or_id>
10. Monitoring Performance
PM2 provides a built-in monitoring dashboard:
pm2 monit
This interactive terminal dashboard displays CPU, memory usage, and event loop delay.
Best Practices
1. Use Cluster Mode for Scalability
Leverage PM2's cluster mode to spawn multiple instances of your Node.js app, maximizing CPU core usage and improving performance.
2. Manage Logs Efficiently
Configure log rotation using PM2's logrotate module to prevent log files from growing indefinitely:
pm2 install pm2-logrotate
Customize logrotate settings as needed to maintain disk space health.
3. Use Environment Variables
Separate environments (development, staging, production) through environment variables in ecosystem files for cleaner configuration management.
4. Regularly Update PM2
Keep PM2 up to date to benefit from the latest features, bug fixes, and security patches:
npm update pm2 -g
5. Automate Deployment
Utilize PM2’s deployment system or integrate with CI/CD pipelines to automate application deployment and reduce manual errors.
6. Monitor Health and Metrics
Use PM2 monitoring combined with external tools (e.g., Keymetrics) for detailed insights and alerting.
Tools and Resources
1. Official PM2 Documentation
The primary source for detailed PM2 features and commands: pm2.keymetrics.io
2. PM2 Logrotate Module
Manage log file sizes automatically: pm2-logrotate GitHub
3. Keymetrics Monitoring Platform
Advanced monitoring and alerting for PM2-managed apps: keymetrics.io
4. Node.js Official Website
Node.js runtime environment information and documentation: nodejs.org
5. Ecosystem File Generator
Use online tools or PM2 CLI to scaffold ecosystem files for complex app configurations.
Real Examples
Example 1: Basic Single Process App
Start a simple Node.js app:
pm2 start server.js --name myserver
Check status:
pm2 list
Example 2: Cluster Mode with Multiple Instances
Run an app with 4 instances to utilize CPU cores:
pm2 start app.js -i 4 --name cluster-app
Example 3: Using Ecosystem File for Multiple Apps
ecosystem.config.js:
module.exports = {
apps: [
{
name: "api-server",
script: "./api.js",
instances: "max",
exec_mode: "cluster",
env: {
NODE_ENV: "production"
}
},
{
name: "worker",
script: "./worker.js",
instances: 1,
exec_mode: "fork",
env: {
NODE_ENV: "production"
}
}
]
}
Start all apps:
pm2 start ecosystem.config.js
Example 4: Setting Up Auto Startup on Ubuntu
Generate startup script:
pm2 startup systemd
Run the command output by PM2 with sudo privileges.
Save current processes:
pm2 save
FAQs
What is PM2 and why use it?
PM2 is a process manager for Node.js apps that keeps them running continuously, manages restarts on failure, and enables load balancing. It simplifies production deployment and monitoring.
Can PM2 manage multiple Node.js applications?
Yes, PM2 can manage multiple applications simultaneously and supports configuration via ecosystem files for easy management.
How do I ensure my Node.js app restarts on server reboot?
Use pm2 startup to generate a startup script and pm2 save to preserve the process list. This configures your system to automatically restart apps on boot.
Does PM2 support zero downtime reloads?
Yes, PM2 supports zero downtime reloads using the cluster mode and the pm2 reload command.
How can I monitor my app’s CPU and memory usage?
Use pm2 monit to access a built-in interactive dashboard with real-time metrics.
Is PM2 suitable for production environments?
Absolutely. PM2 is widely used in production for managing Node.js apps due to its stability, features, and monitoring capabilities.
Conclusion
PM2 is an essential tool that brings robustness, scalability, and ease of management to Node.js applications. From simple process management to advanced features like clustering, log rotation, and automated deployment, PM2 significantly improves the reliability and maintainability of your Node.js apps.
By following this tutorial, you now have the foundational knowledge to install, configure, and optimize PM2 in your development and production environments. Incorporate best practices such as using cluster mode, managing logs, and setting up auto startup to maximize your app’s performance and uptime.
Investing time in mastering PM2 will pay off with smoother deployments, better monitoring, and a more resilient Node.js infrastructure.