阿里云主机折上折
  • 微信号
Current Site:Index > PM2 process management configuration

PM2 process management configuration

Author:Chuan Chen 阅读数:13203人阅读 分类: Node.js

PM2 Process Management Configuration

PM2 is a widely used process management tool in the Node.js ecosystem, helping developers efficiently manage the operation, monitoring, and log collection of Koa2 applications. With PM2, you can achieve multi-process load balancing, automatic restarts, zero-downtime deployments, and more, significantly improving production environment stability.

Installation and Basic Usage

To install PM2 globally, just run one command:

npm install pm2 -g

Basic command to start a Koa2 application:

pm2 start app.js --name "koa-app"

Common basic command examples:

# View running processes
pm2 list

# Monitor process resource usage
pm2 monit

# Stop a specific application
pm2 stop koa-app

# Restart an application
pm2 restart koa-app

# Delete an application
pm2 delete koa-app

Configuration File Details

Configuration files allow finer control over PM2 behavior. Create ecosystem.config.js:

module.exports = {
  apps: [{
    name: 'koa-api',
    script: './app.js',
    instances: 'max',  // Launch maximum processes based on CPU cores
    exec_mode: 'cluster',  // Cluster mode
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'development'
    },
    env_production: {
      NODE_ENV: 'production',
      PORT: 3001
    }
  }]
}

Start with a specific environment:

pm2 start ecosystem.config.js --env production

Advanced Process Management

Load Balancing Configuration

{
  instances: 4,  // Fixed 4 instances
  exec_mode: 'cluster',
  load_balance: true
}

Log Management

{
  error_file: '/var/log/koa-app/err.log',
  out_file: '/var/log/koa-app/out.log',
  combine_logs: true,
  time: true  // Add timestamps to logs
}

Log rotation configuration:

pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 30

Environment Variables and Parameter Passing

Pass environment variables via configuration file:

env: {
  API_KEY: 'your_api_key_here',
  CACHE_TTL: 3600
}

Temporarily override variables at runtime:

pm2 start app.js --update-env -- API_KEY=new_value

Monitoring and Performance Tuning

Built-in monitoring dashboard:

pm2 plus

Custom metric collection example:

const io = require('@pm2/io')

// Custom metric
const reqCounter = io.counter({
  name: 'Requests count'
})

app.use(async (ctx, next) => {
  reqCounter.inc()
  await next()
})

Memory limit configuration:

{
  max_memory_restart: '800M',
  node_args: '--optimize_for_size --max_old_space_size=800'
}

Deployment and Continuous Integration

PM2 deployment configuration example:

deploy: {
  production: {
    user: 'node',
    host: ['server1.example.com', 'server2.example.com'],
    ref: 'origin/master',
    repo: 'git@github.com:user/koa-app.git',
    path: '/var/www/production',
    'post-deploy': 'npm install && pm2 reload ecosystem.config.js --env production',
    env: {
      NODE_ENV: 'production'
    }
  }
}

Execute deployment commands:

pm2 deploy ecosystem.config.js production setup
pm2 deploy ecosystem.config.js production

Error Handling and Debugging

Configure uncaught exception handling:

process.on('unhandledRejection', (reason, p) => {
  console.error('Unhandled Rejection at:', p, 'reason:', reason)
})

process.on('uncaughtException', (err) => {
  console.error('Caught exception:', err)
})

Enable debug mode:

pm2 start app.js --node-args="--inspect=9229"

View specific application logs:

pm2 logs koa-app --lines 200 --timestamp "YYYY-MM-DD HH:mm:ss"

Plugin Ecosystem

Common PM2 plugin examples:

# Database monitoring
pm2 install pm2-mysql

# Redis monitoring
pm2 install pm2-redis

# Email notifications
pm2 install pm2-mail

Custom plugin development template:

module.exports = {
  init: function(pm2) {
    pm2.Client.launchBus(function(err, bus) {
      bus.on('process:event', function(packet) {
        console.log('Process event:', packet.event)
      })
    })
  }
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.