Deploying Node.js Applications with PM2
In modern web development, deploying Node.js applications is a critical step in ensuring stable service operation. Compared to the traditional node start command, using PM2 (Process Manager for Node.js) for production deployment has become an industry-standard practice. PM2 not only supports single-process management but also easily scales to multi-process and cluster modes, offering advanced features such as log monitoring and automatic restarts. This article details how to efficiently deploy Node.js applications using PM2.
Core Advantages and Installation of PM2
PM2 is a powerful production-grade process manager for Node.js that addresses the pain points of traditional startup methods, which cannot handle background daemons, lack log management capabilities, and offer no scalability. Its core advantages include:
- Multi-process Management: Supports both single-process and cluster modes, utilizing multi-core CPUs to enhance performance.
- Automatic Restart Mechanism: Automatically attempts to restart the service when the application crashes or when the port is occupied.
- Log Aggregation: Provides unified tools for viewing and managing logs, facilitating issue troubleshooting.
- Monitoring Dashboard: Includes a built-in web interface to view resource usage and process status in real-time.
First, you need to install PM2 within your project. It is recommended to use npm for global or local installation:
npm install -g pm2
# Alternatively, install locally at the root of the project to enhance dependency management
npm install pm2 --save-dev
Basic Deployment Workflow
After completing the installation, create app.js as the entry file. Below is a simple example code snippet:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Node.js with PM2!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
To start the application, simply use the pm2 start command. PM2 will automatically run the process in the background and assign a unique Process ID (PID). At this point, you can view all started processes and their status using pm2 list. If you need to stop a specific process, use pm2 stop <pid>; if you wish to completely uninstall the application, execute pm2 delete <pid>.
Cluster Mode Deployment and Load Balancing
For high-concurrency scenarios, a single process often fails to meet requirements. PM2 provides built-in cluster functionality that automatically allocates the number of processes based on the CPU core count. The command to enable cluster mode is as follows:
pm2 start app.js --cluster
In cluster mode, PM2 launches multiple child processes, each listening on a different port (starting from 3001 by default), thereby fully utilizing multi-core CPU resources. This mode not only improves response speed but also enhances system fault tolerance—if one node fails, other nodes can continue to serve requests.
Configuring Production Environment Parameters
To adapt to the specific requirements of the production environment, you can customize PM2 behavior through configuration files or command-line parameters. For example, you can set maximum memory limits, enable log rotation, or adjust health check strategies:
pm2 start app.js --max-memory-restart 100M --time-limit 60s
Additionally, PM2 supports defining multi-environment configurations (development, testing, production) via the ecosystem.config.js file, enabling one-click switching of deployment modes. Within ecosystem.config.js, you can precisely control startup parameters for each process, listening ports, and resource limits.
Log Management and Monitoring
In a production environment, the readability and traceability of logs are crucial. PM2 provides convenient commands for viewing logs:
pm2 logs <pid>
# Or track the output of a specific process in real-time
pm2 monit <pid>
The pm2 monit command continuously outputs the CPU, memory, and network usage of the process, helping developers quickly identify performance bottlenecks. Combined with PM2's Web management dashboard (by adding the --web parameter at startup), administrators can remotely access deployment status and real-time log streams without needing an SSH login for global monitoring.
Summary and Best Practices
Deploying Node.js applications with PM2 not only simplifies daily operations but also significantly enhances system stability and scalability. It is recommended to always enable cluster mode in production environments and configure reasonable resource limits to prevent memory overflow. Additionally, regularly use the pm2 save command to save the current process state, ensuring that services can automatically resume after a restart. Mastering these techniques will help you build more robust backend architectures.