How to Use Pm2 for Nodejs
Introduction PM2 is a powerful process manager for Node.js applications that helps developers manage and keep their apps alive forever. Whether you are running a small Node.js project or a large-scale production application, PM2 simplifies the deployment, monitoring, and maintenance process. Using PM2 enhances application reliability by automatically restarting crashed processes, enabling load bal
Introduction
PM2 is a powerful process manager for Node.js applications that helps developers manage and keep their apps alive forever. Whether you are running a small Node.js project or a large-scale production application, PM2 simplifies the deployment, monitoring, and maintenance process.
Using PM2 enhances application reliability by automatically restarting crashed processes, enabling load balancing, and offering detailed logs and monitoring capabilities. This tutorial will provide a comprehensive guide on how to use PM2 with Node.js, covering installation, configuration, best practices, and real-world examples to help you master this essential tool.
Step-by-Step Guide
1. Installing PM2
Before using PM2, ensure you have Node.js and npm installed on your system. You can verify this by running:
node -v and npm -v
To install PM2 globally, run the following command:
npm install pm2 -g
This installs PM2 as a global package, allowing you to run it from any directory.
2. Starting a Node.js Application with PM2
Navigate to your Node.js project directory and start your application using PM2:
pm2 start app.js
Replace app.js with the entry file of your Node.js application.
PM2 will start your app and assign it a process ID. The app will continue running in the background, even if you close your terminal.
3. Managing Processes
PM2 provides several commands to manage running applications:
- pm2 list Displays all running processes managed by PM2.
- pm2 stop <id|name> Stops a process by its ID or name.
- pm2 restart <id|name> Restarts a process.
- pm2 delete <id|name> Stops and removes a process from PM2.
4. Monitoring Applications
To monitor your apps CPU and memory usage in real-time, use:
pm2 monit
This interactive dashboard provides valuable insights into your apps performance and resource consumption.
5. Enabling Startup Script for System Reboots
To ensure your Node.js app starts automatically after a server reboot, generate and configure a startup script with PM2:
pm2 startup
Follow the instructions that PM2 outputs to set up the startup system service correctly.
Then save the current process list:
pm2 save
This saves the list of processes to be resurrected on system boot.
6. Managing Logs
PM2 automatically manages logs for your applications. To view logs:
pm2 logs
To view logs for a specific app:
pm2 logs <id|name>
You can also specify log file locations in ecosystem files (covered later).
7. Using the Ecosystem File
An ecosystem file is a JSON or JavaScript configuration file where you define your apps configuration, environments, and deployment settings.
Create a basic ecosystem file with:
pm2 init
This generates ecosystem.config.js. You can define multiple apps, environment variables, and settings like:
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 using ecosystem file:
pm2 start ecosystem.config.js --env production
Best Practices
1. Use Cluster Mode for Performance
PM2 supports cluster mode, which allows your Node.js app to run multiple instances to utilize all CPU cores efficiently:
pm2 start app.js -i max
This launches as many instances as CPU cores available, improving performance and fault tolerance.
2. Keep Ecosystem File Under Version Control
Maintain your ecosystem configuration file in your projects source control repository to ensure consistent deployment environments.
3. Monitor Memory Usage and Restart Automatically
Set memory thresholds to automatically restart apps if they consume excessive memory:
pm2 start app.js --max-memory-restart 200M
This prevents memory leaks from impacting application stability.
4. Set Up Log Rotation
Logs can grow indefinitely, consuming disk space. Use PM2s log rotation module:
pm2 install pm2-logrotate
Configure rotation parameters to maintain manageable log sizes.
5. Use Environment Variables
Differentiate between development and production environments using environment variables in your ecosystem file. This keeps configurations clean and manageable.
6. Regularly Update PM2
Keep PM2 updated to benefit from the latest features and security patches:
npm install pm2@latest -g
Tools and Resources
1. Official PM2 Documentation
The primary source of detailed information and updates: https://pm2.keymetrics.io/
2. PM2 Logrotate Module
Manage your application logs effectively with this module: Log Management
3. Keymetrics Monitoring Dashboard
PM2 integrates with Keymetrics, a monitoring platform for Node.js apps, offering advanced visualization and alerting: https://keymetrics.io/
4. Node.js Official Website
For Node.js downloads, documentation, and tutorials: https://nodejs.org/
5. PM2 GitHub Repository
Explore source code, raise issues, and contribute: https://github.com/Unitech/pm2
Real Examples
Example 1: Starting a Simple App
You have a basic server.js file running an Express app. To start it with PM2:
pm2 start server.js
This ensures the app runs in the background, restarts on failure, and logs are accessible through PM2.
Example 2: Running Multiple Instances in Cluster Mode
To launch four instances of your app to maximize CPU usage:
pm2 start server.js -i 4 --name "my-cluster-app"
This runs your app in cluster mode under the name my-cluster-app.
Example 3: Using an Ecosystem File for Multiple Apps
Setup ecosystem.config.js for two apps:
module.exports = {
apps: [
{
name: "api-server",
script: "./api.js",
instances: 2,
exec_mode: "cluster"
},
{
name: "worker",
script: "./worker.js",
instances: 1
}
]
};
Start both apps at once:
pm2 start ecosystem.config.js
Example 4: Auto-Restart on Memory Leak
Automatically restart an app if it uses more than 300MB RAM:
pm2 start app.js --max-memory-restart 300M
FAQs
What is PM2 and why should I use it?
PM2 is a process manager for Node.js applications that keeps your app alive, manages logs, and facilitates load balancing and monitoring. It ensures high availability and simplifies deployment.
Can PM2 manage multiple Node.js applications simultaneously?
Yes, PM2 can manage multiple applications or multiple instances of the same app, making it ideal for microservices or clustered deployments.
How do I make sure my app restarts after a server reboot?
Use the pm2 startup command to generate a startup script and save your process list with pm2 save. This ensures PM2 resurrects your apps after reboot.
Is it possible to use PM2 with Docker?
Yes, PM2 can be used inside Docker containers to manage Node.js processes, but often it's recommended to let Docker handle process management. PM2 can still be useful for clustering and graceful reloads inside containers.
How can I monitor my Node.js apps performance with PM2?
Use pm2 monit for real-time monitoring or integrate with Keymetrics for advanced dashboards and alerts.
Does PM2 support environment variables?
Yes, environment variables can be defined in the ecosystem file or passed directly via CLI, enabling different configurations for development, testing, and production.
Conclusion
PM2 is an indispensable tool for Node.js developers seeking to run their applications reliably in production environments. Its ease of use, combined with powerful features like process management, clustering, monitoring, and log handling, makes it a top choice for managing Node.js apps.
By following the step-by-step guide and adhering to best practices outlined in this tutorial, you can ensure your Node.js applications are robust, scalable, and maintainable. Explore PM2s ecosystem file and monitoring integrations to fully leverage its capabilities and keep your apps running smoothly.