PM2 Fundamentals: Complete Installation and Setup Guide for Ubuntu Server

PM2 Fundamentals: Complete Installation and Setup Guide for Ubuntu Server

This entry is part 1 of 7 in the series PM2 Mastery: From Zero to Production Hero

Process management is the backbone of any production Node.js application. When your application crashes, who restarts it? When your server reboots, how do your applications come back online? This is where PM2 (Process Manager 2) becomes indispensable for Ubuntu server administrators and Node.js developers.

What is PM2 and Why Do You Need It?

PM2 is a daemon process manager that helps you manage and keep your Node.js applications online 24/7. Think of it as a guardian angel for your applications – it watches over them, restarts them if they crash, and provides powerful monitoring and logging capabilities.

graph TD
    A[Node.js Application] --> B[PM2 Process Manager]
    B --> C[Automatic Restart]
    B --> D[Load Balancing]
    B --> E[Monitoring]
    B --> F[Log Management]
    B --> G[Zero-Downtime Reload]
    
    C --> H[Application Always Online]
    D --> I[Better Performance]
    E --> J[Health Monitoring]
    F --> K[Centralized Logs]
    G --> L[Seamless Updates]

Key Benefits of PM2

  • Automatic Restart: Applications restart automatically if they crash
  • Cluster Mode: Utilize all CPU cores with built-in load balancer
  • Zero-Downtime Deployments: Update applications without service interruption
  • Process Monitoring: Real-time monitoring of CPU and memory usage
  • Log Management: Centralized logging with automatic log rotation
  • Startup Script: Auto-start applications on server boot

Prerequisites: Setting Up Your Ubuntu Environment

Before installing PM2, ensure your Ubuntu server has Node.js properly configured. Here’s the recommended setup process:

Installing Node.js on Ubuntu

# Method 1: Using NodeSource Repository (Recommended)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs

# Method 2: Using Node Version Manager (NVM)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
source ~/.bashrc
nvm install --lts
nvm use --lts

# Verify installation
node --version
npm --version
flowchart LR
    A[Ubuntu Server] --> B{Node.js Installed?}
    B -->|No| C[Install Node.js]
    B -->|Yes| D[Check Version]
    C --> E[NodeSource Repo]
    C --> F[NVM Method]
    C --> G[Package Manager]
    E --> H[PM2 Installation]
    F --> H
    G --> H
    D --> I{Version Compatible?}
    I -->|Yes| H
    I -->|No| J[Update Node.js]
    J --> H

PM2 Installation Methods

PM2 can be installed through multiple methods. Each has its advantages depending on your use case:

Method 1: Global NPM Installation (Recommended)

# Install PM2 globally
sudo npm install -g pm2

# Verify installation
pm2 --version

# Check PM2 status
pm2 status

Method 2: Using Yarn

# Install Yarn if not already installed
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt update && sudo apt install yarn

# Install PM2 with Yarn
sudo yarn global add pm2

Method 3: Ubuntu Package Manager (Limited)

# Note: This may install an older version
sudo apt update
sudo apt install pm2

# Check installed version
pm2 --version

Essential PM2 Commands

Once PM2 is installed, these are the fundamental commands you’ll use daily:

graph LR
    A[PM2 Commands] --> B[Process Management]
    A --> C[Information]
    A --> D[Logs]
    A --> E[Monitoring]
    
    B --> B1[pm2 start]
    B --> B2[pm2 stop]
    B --> B3[pm2 restart]
    B --> B4[pm2 delete]
    B --> B5[pm2 reload]
    
    C --> C1[pm2 list]
    C --> C2[pm2 info]
    C --> C3[pm2 describe]
    
    D --> D1[pm2 logs]
    D --> D2[pm2 flush]
    
    E --> E1[pm2 monit]
    E --> E2[pm2 status]

Process Management Commands

# Start an application
pm2 start app.js
pm2 start app.js --name "my-app"

# Stop applications
pm2 stop app.js
pm2 stop 0          # Stop by process ID
pm2 stop all        # Stop all processes

# Restart applications
pm2 restart app.js
pm2 restart all

# Reload applications (zero-downtime)
pm2 reload app.js
pm2 reload all

# Delete applications from PM2
pm2 delete app.js
pm2 delete all

Information and Monitoring Commands

# List all processes
pm2 list
pm2 ls

# Show detailed information about a process
pm2 describe 0
pm2 info my-app

# Monitor processes in real-time
pm2 monit

# Show process status
pm2 status

Your First Application Deployment

Let’s create a simple Express.js application and deploy it with PM2 to understand the basics:

Creating a Sample Application

# Create project directory
mkdir pm2-demo
cd pm2-demo

# Initialize Node.js project
npm init -y

# Install Express.js
npm install express

# Create app.js
cat > app.js << 'EOF'
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.json({
    message: 'Hello from PM2!',
    timestamp: new Date().toISOString(),
    process: process.pid,
    uptime: process.uptime()
  });
});

app.get('/health', (req, res) => {
  res.json({
    status: 'healthy',
    memory: process.memoryUsage(),
    uptime: process.uptime()
  });
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
EOF

Deploying with PM2

# Start the application with PM2
pm2 start app.js --name "demo-app"

# Start with custom options
pm2 start app.js --name "demo-app" --instances 2 --env production

# Check if it's running
pm2 list

# Test the application
curl http://localhost:3000
curl http://localhost:3000/health
sequenceDiagram
    participant U as User
    participant PM2 as PM2 Manager
    participant App as Node.js App
    participant S as System
    
    U->>PM2: pm2 start app.js
    PM2->>App: Launch Process
    App->>S: Bind to Port 3000
    S-->>App: Port Bound Successfully
    App-->>PM2: Process Started (PID)
    PM2-->>U: Application Running
    
    U->>PM2: pm2 list
    PM2-->>U: Show Process Status
    
    U->>App: HTTP Request (curl)
    App-->>U: JSON Response

Basic Monitoring and Logging

PM2 provides excellent built-in monitoring and logging capabilities that are essential for production applications:

Real-time Monitoring

# Launch monitoring interface
pm2 monit

# View process information
pm2 show demo-app

# Check memory and CPU usage
pm2 list

Log Management

# View logs in real-time
pm2 logs
pm2 logs demo-app

# View specific number of lines
pm2 logs --lines 100

# Clear all logs
pm2 flush

# Log file locations
ls ~/.pm2/logs/

Common Installation Issues and Solutions

Here are the most common issues you might encounter during PM2 installation and their solutions:

Permission Issues

# If you get permission errors
sudo chown -R $(whoami) ~/.npm
sudo chown -R $(whoami) /usr/local/lib/node_modules

# Alternative: Use npm prefix
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc

PATH Issues

# Check if PM2 is in PATH
which pm2

# Add to PATH if needed
echo 'export PATH=$PATH:/usr/local/bin' >> ~/.bashrc
source ~/.bashrc

# Verify installation
pm2 --version

Node.js Version Conflicts

# Check Node.js version
node --version

# PM2 requires Node.js >= 16.x
# Update if necessary using NVM
nvm install --lts
nvm use --lts

# Reinstall PM2 after Node.js update
npm uninstall -g pm2
npm install -g pm2

Verification and Testing

Let’s verify that everything is working correctly with a comprehensive test:

# Complete verification script
echo "=== PM2 Installation Verification ==="

echo "1. Checking PM2 version:"
pm2 --version

echo "2. Checking Node.js version:"
node --version

echo "3. Starting test application:"
pm2 start app.js --name "test-app"

echo "4. Checking process list:"
pm2 list

echo "5. Testing application response:"
sleep 2
curl http://localhost:3000

echo "6. Checking logs:"
pm2 logs test-app --lines 5

echo "7. Cleanup:"
pm2 delete test-app

echo "=== Verification Complete ==="

What’s Next?

Congratulations! You now have PM2 installed and running on your Ubuntu server. You’ve learned the fundamental commands and deployed your first application. In the next part of this series, we’ll dive deep into PM2 configuration mastery, covering:

  • Creating comprehensive ecosystem.config.js files
  • Managing multiple environments (dev, staging, production)
  • Advanced configuration options and best practices
  • Environment variable management
  • Application-specific settings and optimizations

This foundation knowledge will serve you well as we explore more advanced PM2 features. Make sure to bookmark this series and practice these commands on your Ubuntu server!

Series Navigation:
← Part 1: PM2 Fundamentals (You are here)
→ Part 2: Configuration Mastery (Coming next)

NavigatePM2 Configuration Mastery: Ecosystem Files and Environment Management >>

Written by:

387 Posts

View All Posts
Follow Me :