PM2 is a popular process manager for Node.js applications. It allows you to keep your applications alive forever, reload them without downtime, and facilitate common system admin tasks.

Key Concepts

  1. Process Management: PM2 helps manage and monitor Node.js applications, ensuring they run continuously.
  2. Load Balancing: PM2 can distribute incoming traffic across multiple instances of your application.
  3. Monitoring: PM2 provides real-time monitoring and logging of your applications.
  4. Deployment: PM2 simplifies the deployment process with built-in support for various deployment strategies.

Setting Up PM2

Installation

To install PM2 globally on your system, use the following command:

npm install -g pm2

Starting an Application

To start a Node.js application with PM2, use the start command:

pm2 start app.js

Listing Processes

To list all running processes managed by PM2, use:

pm2 list

Stopping an Application

To stop a specific application, use the stop command followed by the process ID or name:

pm2 stop app.js

Restarting an Application

To restart an application, use the restart command:

pm2 restart app.js

Deleting a Process

To delete a process from PM2's list, use the delete command:

pm2 delete app.js

Practical Example

Let's create a simple Node.js application and manage it with PM2.

Step 1: Create a Simple Node.js Application

Create a file named app.js with the following content:

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, World!\n');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

Step 2: Start the Application with PM2

Start the application using PM2:

pm2 start app.js

Step 3: Monitor the Application

List the running processes to see your application:

pm2 list

You should see an output similar to this:

┌─────┬──────┬────────┬───┬─────┬───────────┬────────┬─────────────┬──────────┐
│ id  │ name │ mode   │ ↺ │ status │ cpu      │ memory │
├─────┼──────┼────────┼───┼─────┼───────────┼────────┼─────────────┼──────────┤
│ 0   │ app  │ fork   │ 0 │ online │ 0%       │ 20.0mb │
└─────┴──────┴────────┴───┴─────┴───────────┴────────┴─────────────┴──────────┘

Step 4: Stop the Application

Stop the application using PM2:

pm2 stop app.js

Step 5: Restart the Application

Restart the application using PM2:

pm2 restart app.js

Step 6: Delete the Application

Delete the application from PM2's list:

pm2 delete app.js

Advanced Features

Load Balancing

PM2 can run multiple instances of your application to handle more traffic. Use the -i option to specify the number of instances:

pm2 start app.js -i 4

Monitoring and Logs

PM2 provides real-time monitoring and logging. Use the following commands to access these features:

  • Monitor: pm2 monit
  • Logs: pm2 logs

Auto-Restart on File Changes

PM2 can automatically restart your application when it detects file changes. Use the --watch option:

pm2 start app.js --watch

Practical Exercise

Exercise

  1. Create a simple Node.js application that responds with "Hello, PM2!".
  2. Start the application using PM2.
  3. Monitor the application using PM2.
  4. Stop and restart the application using PM2.
  5. Enable auto-restart on file changes.

Solution

  1. Create a file named app.js with the following content:

    const http = require('http');
    
    const server = http.createServer((req, res) => {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('Hello, PM2!\n');
    });
    
    server.listen(3000, () => {
      console.log('Server running at http://localhost:3000/');
    });
    
  2. Start the application using PM2:

    pm2 start app.js
    
  3. Monitor the application using PM2:

    pm2 monit
    
  4. Stop and restart the application using PM2:

    pm2 stop app.js
    pm2 restart app.js
    
  5. Enable auto-restart on file changes:

    pm2 start app.js --watch
    

Conclusion

In this section, you learned how to use PM2 for process management in Node.js applications. You covered installation, starting, stopping, restarting, and deleting processes, as well as advanced features like load balancing, monitoring, and auto-restart on file changes. These skills will help you manage and monitor your Node.js applications effectively, ensuring they run smoothly in production environments.

Node.js Course

Module 1: Introduction to Node.js

Module 2: Core Concepts

Module 3: File System and I/O

Module 4: HTTP and Web Servers

Module 5: NPM and Package Management

Module 6: Express.js Framework

Module 7: Databases and ORMs

Module 8: Authentication and Authorization

Module 9: Testing and Debugging

Module 10: Advanced Topics

Module 11: Deployment and DevOps

Module 12: Real-World Projects

© Copyright 2024. All rights reserved