How to Install and Use PM2 in Ubuntu

In the modern world of web development, where milliseconds matter and downtime is a four-letter word, ensuring your Node.js application is always running, monitored, and performant is non-negotiable. For developers and system administrators working with Node.js, the industry-standard solution is almost universally the same: PM2.

PM2, which stands for Process Manager 2, is a powerful, production-ready process manager with a built-in load balancer for Node.js applications. It simplifies managing your applications on a server, providing essential features like automatic restarts on failure, zero-downtime reloads, and easy, real-time monitoring.

If you’re running a Node.js application directly with the node app.js command, you’re one crash away from a complete outage. This exhaustive guide will walk you through everything you need to know, from the initial installation on an Ubuntu server to advanced configurations that guarantee your application runs flawlessly 24/7.


1. The ‘Why’ Behind PM2: Reliability in Production

Why can’t you just use node? Node.js applications, by default, run as a single process. This single-process architecture creates two major vulnerabilities in a production environment:

  1. Single Point of Failure (SPOF): If your Node.js process encounters an unhandled exception or crash, the entire application shuts down immediately, leading to downtime until you manually restart it.
  2. Underutilization of Resources: A single Node.js process can only utilize one core of your server’s CPU. If you’re paying for a powerful machine with 4, 8, or 16 cores, you’re leaving most of your computational power sitting idle.

PM2 Solves These Problems:

  • High Availability (Auto-Restart): PM2 runs your application as a daemon process and constantly monitors it. If it crashes, PM2 immediately restarts it. It keeps your app “alive forever.”
  • Scalability (Cluster Mode): PM2 leverages the built-in Node.js cluster module to efficiently spawn and manage multiple instances of your application, one for each CPU core. It then acts as an intelligent load balancer, maximizing your server’s throughput.
  • System Integration: It can generate a startup script that integrates with Ubuntu’s Systemd, ensuring your applications are launched automatically after the server reboots.

In short, PM2 transforms a simple Node.js script into a robust, scalable, and self-healing production service.


2. Prerequisites: Getting Your Ubuntu Server Ready

Before installing PM2, you need a recent, stable Ubuntu server and a working Node.js environment.

💻 System Checklist:

  • Operating System: Any recent version of Ubuntu (e.g., 20.04 LTS, 22.04 LTS, or newer).
  • User: A non-root user with sudo privileges is essential for security best practices.
  • Node.js & npm: PM2 is installed via the Node Package Manager (npm).

Installing Node.js (The NodeSource Method)

While you can install Node.js via the default Ubuntu repositories (apt), it often provides an outdated version. Using the official NodeSource repository is the most reliable way to get a recent LTS version.

First, update your local package index and install curl:

Bash

sudo apt update
sudo apt install curl -y

Next, use the NodeSource setup script to add their repository for the latest Long-Term Support (LTS) version, and then install Node.js. (Note: The setup_lts.x script will dynamically find the current LTS version).

Bash

curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install nodejs -y

Verify that both Node.js and npm are correctly installed:

Bash

node -v
npm -v

You should see the version numbers for both tools.


3. The Core PM2 Installation and First Run

Once Node.js and npm are confirmed to be working, installing PM2 is a single, straightforward command executed globally.

Step 1: Install PM2 Globally

Use npm to install the latest stable version of PM2 globally (-g). We use sudo here because we are installing the package into a system-wide directory.

Bash

sudo npm install pm2@latest -g

Step 2: Verification and Health Check

To ensure PM2 is successfully installed and accessible from any location on your system, check its version:

Bash

pm2 --version

Step 3: Run Your First Node.js Application

For this example, assume you have a file named server.js (or app.js) in your project directory. Navigate to your project folder and start the application:

Bash

# Start your application in the default 'fork' mode
pm2 start server.js --name "MyWebApp-API"

The --name flag is a crucial best practice, allowing you to manage the application easily by its memorable name rather than a cryptic process ID.

Step 4: Check the Process List

Immediately check the status of your application using the list command:

Bash

pm2 list
IDNameModeStatusCPUMemory
0MyWebApp-APIforkonline00.0%30.0MB

If the Status shows online, congratulations! Your application is now running as a persistent daemon process. If it shows errored, check the logs immediately (see Section 4).


4. Essential Daily PM2 Management Commands

PM2 acts as a command-line interface (CLI) control panel for your processes. Mastering these fundamental commands is key to efficient application maintenance.

⚙️ Lifecycle Management

CommandActionKey BenefitExample
pm2 restartStops and immediately restarts the app.Quick fix for minor issues or code deployment.pm2 restart MyWebApp-API
pm2 reloadZero-Downtime Reload. Starts the new process, and only once it’s confirmed online does it kill the old process.Critical for public-facing applications; prevents connection drops.pm2 reload MyWebApp-API
pm2 stopStops the application process, but keeps it in the PM2 list (ready to be restarted).Temporarily take the app offline for maintenance.pm2 stop MyWebApp-API
pm2 deleteStops the application and completely removes it from the PM2 process list.Permanent removal of an application.pm2 delete MyWebApp-API
pm2 killStops and removes all managed processes and shuts down the PM2 daemon itself.Only use this if you need to completely reset the PM2 environment.pm2 kill

🔍 Real-Time Monitoring and Logging

When an application crashes or consumes too many resources, the logs are your first line of defense.

  • View Logs in Real-time: This command streams the combined stdout (console output) and stderr (errors) for all managed applications.Bashpm2 logs
  • View Specific Application Logs:Bashpm2 logs MyWebApp-API --lines 100 (The --lines 100 flag shows the last 100 lines before streaming begins.)
  • The PM2 Dashboard (Monit): For a beautiful, interactive, terminal-based dashboard displaying real-time CPU, Memory, and log activity, run:Bashpm2 monit This utility provides the clearest overview of your server’s performance under the PM2 umbrella.

5. Advanced Configuration: The Production Toolkit

To truly be production-ready, you must configure PM2 to handle multi-core systems and server reboots.

🌐 Cluster Mode: Unlocking Full CPU Power

If your server has more than one CPU core, you must run your Node.js application in Cluster Mode to utilize that capacity. PM2 automatically handles the complexity of load balancing for you.

To start your application in cluster mode:

Bash

# Start one instance for every available CPU core on your server
pm2 start server.js -i max --name "App-Cluster-Prod"

# Alternatively, specify a fixed number of instances (e.g., 4)
# pm2 start server.js -i 4 --name "App-Cluster-Prod"

Running pm2 list now will show multiple processes with the same name, each with its own ID, working in concert. This is the difference between a high-traffic app failing and scaling effortlessly.

💾 Persistence: Autostart on Server Reboot

By default, PM2 processes are running in memory. If your server reboots (due to an OS update, maintenance, or unexpected crash), PM2 and your applications will not automatically restart. You must configure PM2 to integrate with the Ubuntu Systemd init system.

This is a critical two-step process: Generate the Systemd script and then Save the running process list.

Step 1: Generate the Startup Script

Run the pm2 startup command. PM2 is smart enough to detect Ubuntu’s Systemd and generate a specific command tailored to your user and system paths.

Bash

pm2 startup

PM2 will output a specific command that looks something like this (but with your unique paths):

[PM2] To setup the Startup Script, copy/paste the following command:
sudo env PATH=$PATH:/home/user/.nvm/versions/node/v20.11.0/bin /home/user/.nvm/versions/node/v20.11.0/lib/node_modules/pm2/bin/pm2 startup systemd -u your-username --hp /home/your-username

CRITICAL: You must copy the entire, long sudo env PATH... command that PM2 provides and paste it back into your terminal and run it. This registers the PM2 service with Systemd.

Step 2: Save the Current Process List

This tells PM2 exactly which applications it needs to resurrect upon server boot.

Bash

pm2 save

This command saves the current state of pm2 list to a configuration file on disk. When the server reboots, the Systemd script will start the PM2 daemon, and the daemon will use this saved list to bring all your apps back online.


6. The Ecosystem File: Production Standardization

While running apps via the command line is fine for one or two processes, a PM2 Ecosystem File (ecosystem.config.js) is the industry standard for production deployments. This single file defines all application parameters (cluster count, environment variables, logs, memory limits) in a clean, portable, and version-controlled way.

Step 1: Generate the Template

PM2 can generate a template file for you:

Bash

pm2 init

This creates a file named ecosystem.config.js in your current directory.

Step 2: Configure for Production and Development

Open the file and configure it. Notice how we can define separate configurations for different environments using env_production and env_development.

JavaScript

module.exports = {
  apps: [{
    name: "MyWebApp-API", 
    script: "server.js", 
    instances: "max", 
    exec_mode: "cluster", 
    watch: false, // Set to true only for development
    log_date_format: "YYYY-MM-DD HH:mm:ss Z",
    error_file: "logs/api-error.log",
    out_file: "logs/api-out.log",

    // Environment for Production
    env_production: {
      NODE_ENV: "production",
      PORT: 8080,
      DB_HOST: "prod.database.com",
    },
    // Environment for Local Development/Staging
    env_development: {
      NODE_ENV: "development",
      PORT: 3000,
      DB_HOST: "dev.database.com",
    }
  }]
};

Step 3: Start Applications using the Configuration

You no longer need long command-line arguments. Simply specify the file and the environment:

Bash

# Delete any old version running
pm2 delete MyWebApp-API

# Start the app using the ecosystem file in production mode
pm2 start ecosystem.config.js --env production

This ensures consistent and repeatable deployments every single time.


7. Security and Maintenance Best Practices

🔑 Security: Use an Unprivileged User

  • Reverse Proxy is Key: Never run your Node.js application as the root user, even when using PM2. This is a severe security risk.
  • The Solution: Run your application on a high, unprivileged port (e.g., 8080 in the configuration above). Then, use a reverse proxy like Nginx or Apache, which runs as a privileged user, to handle requests on ports 80 (HTTP) and 443 (HTTPS) and forward them internally to your Node.js app’s port.

🛠️ Maintenance: Updating PM2

Keeping PM2 updated is a simple two-step process that ensures you have the latest features and stability patches:

  1. Update the Global Package:Bashsudo npm install pm2@latest -g
  2. Update the Daemon: This command safely saves your current process list, kills the old PM2 daemon, and restarts it using the newly installed binary, bringing all your processes back online automatically.Bashpm2 update

🛑 Troubleshooting Common Issues

IssueDescriptionSolution
Status: erroredYour app crashed immediately.The first step is always to check the logs: pm2 logs <app_name>. Look for database connection errors, missing environment variables, or dependency issues.
PM2 doesn’t restart on bootThe server rebooted, but pm2 list is empty or apps are stopped.You likely forgot to save the process list. Run pm2 save after starting your apps, and ensure you ran the pm2 startup command (including the long sudo env PATH... output) correctly.
pm2 command not foundPM2 is installed, but the shell doesn’t recognize it.If you used nvm, ensure the shell configuration is loaded (source ~/.bashrc). If not, check that you installed it with sudo npm install -g pm2.

Conclusion: You Are Now Production-Ready!

Congratulations! By following this comprehensive guide, you’ve done much more than just run an installation command. You have successfully implemented a robust process management strategy on your Ubuntu server that guarantees:

  • Minimal Downtime
  • Maximum CPU Utilization (via Cluster Mode)
  • Automatic Recovery (via Auto-Restart)
  • Persistence (via Systemd startup script)

PM2 is the silent guardian of your Node.js application, allowing you to deploy with confidence. Your application now has the foundation required to handle real-world production traffic reliably.


That’s a great comprehensive guide! To maximize its visibility and search engine optimization (SEO), here are the best tags for your blog post, “Mastering Production: A Comprehensive Guide on How to Install and Use PM2 in Ubuntu.”

These tags are categorized by relevance and topic depth:

🏷️ Tags

  • pm2
  • pm2 install
  • pm2 ubuntu
  • Node.js
  • Node.js Production
  • Process Manager


Leave a Reply

Your email address will not be published. Required fields are marked *