PM2 ist ein Produktions-Prozessmanager für Node.js-Anwendungen. Er bietet automatische Restarts, Clustering, Logging und Zero-Downtime-Deployments.

Features

Übersicht

- Prozess-Management
- Automatischer Neustart bei Crashes
- Cluster-Modus (Multi-Core)
- Zero-Downtime Reload
- Integriertes Logging
- Startup-Skripte
- Monitoring-Dashboard
- Deployment-System

Installation

Global

npm install pm2 -g

Version prüfen

pm2 --version

Anwendung starten

Einfacher Start

pm2 start app.js

Mit Optionen

pm2 start app.js --name "myapp" --watch --max-memory-restart 200M

Interpreter angeben

# Python
pm2 start script.py --interpreter python3

# PHP
pm2 start script.php --interpreter php

Cluster-Modus

# Alle CPU-Kerne
pm2 start app.js -i max

# Bestimmte Anzahl
pm2 start app.js -i 4

Prozess-Verwaltung

Status anzeigen

pm2 list
pm2 status

Prozesse steuern

# Stoppen
pm2 stop app
pm2 stop all

# Neustarten
pm2 restart app
pm2 restart all

# Reload (Zero-Downtime)
pm2 reload app
pm2 reload all

# Löschen
pm2 delete app
pm2 delete all

Einzelne Prozesse

# Nach Name
pm2 restart myapp

# Nach ID
pm2 restart 0

Ecosystem-Datei

ecosystem.config.js

// ecosystem.config.js

module.exports = {
  apps: [
    {
      name: 'api',
      script: './api/server.js',
      instances: 'max',
      exec_mode: 'cluster',
      watch: false,
      max_memory_restart: '500M',
      env: {
        NODE_ENV: 'development',
        PORT: 3000
      },
      env_production: {
        NODE_ENV: 'production',
        PORT: 8080
      }
    },
    {
      name: 'worker',
      script: './worker/index.js',
      instances: 2,
      exec_mode: 'cluster',
      cron_restart: '0 0 * * *',
      env: {
        NODE_ENV: 'production'
      }
    },
    {
      name: 'frontend',
      script: 'npm',
      args: 'start',
      cwd: './frontend',
      env: {
        NODE_ENV: 'production'
      }
    }
  ]
};

Mit Ecosystem starten

pm2 start ecosystem.config.js
pm2 start ecosystem.config.js --env production

Konfigurationsoptionen

Wichtige Optionen

| Option | Beschreibung | |--------|--------------| | name | Prozess-Name | | script | Skript-Pfad | | instances | Anzahl Instanzen | | exec_mode | fork oder cluster | | watch | Datei-Watcher | | max_memory_restart | Neustart bei RAM-Limit | | cron_restart | Zeitbasierter Restart | | env | Umgebungsvariablen | | log_date_format | Log-Zeitformat | | error_file | Fehler-Log-Pfad | | out_file | Stdout-Log-Pfad | | merge_logs | Logs zusammenführen |

Erweiterte Optionen

{
  name: 'app',
  script: './app.js',
  instances: 4,
  exec_mode: 'cluster',

  // Restart-Verhalten
  max_restarts: 10,
  min_uptime: '10s',
  restart_delay: 4000,

  // Logs
  log_date_format: 'YYYY-MM-DD HH:mm:ss',
  error_file: '/var/log/pm2/app-error.log',
  out_file: '/var/log/pm2/app-out.log',
  merge_logs: true,

  // Graceful Shutdown
  kill_timeout: 5000,
  listen_timeout: 8000,
  shutdown_with_message: true,

  // Source Maps
  source_map_support: true,

  // Node.js Args
  node_args: '--max-old-space-size=4096',

  // Watch
  watch: ['src'],
  ignore_watch: ['node_modules', 'logs'],
  watch_delay: 1000
}

Logging

Logs anzeigen

# Alle Logs
pm2 logs

# Spezifische App
pm2 logs myapp

# Letzte N Zeilen
pm2 logs --lines 200

Log-Management

# Logs rotieren
pm2 install pm2-logrotate

# Logs leeren
pm2 flush

Log-Rotation konfigurieren

pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 30
pm2 set pm2-logrotate:compress true
pm2 set pm2-logrotate:dateFormat YYYY-MM-DD_HH-mm-ss

Monitoring

Terminal-Monitoring

pm2 monit

Dashboard (PM2 Plus)

pm2 plus

Metriken

pm2 show myapp

# CPU/Memory
pm2 info myapp

Startup-Skript

Systemstart konfigurieren

# Startup-Skript generieren
pm2 startup

# Ausführen (als root)
sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u user --hp /home/user

# Aktuelle Prozesse speichern
pm2 save

Startup entfernen

pm2 unstartup systemd

Zero-Downtime-Deployment

Graceful Reload

// In app.js
process.on('SIGINT', function() {
  // Cleanup
  server.close(function() {
    process.exit(0);
  });

  // Force close nach Timeout
  setTimeout(function() {
    process.exit(1);
  }, 5000);
});
# Reload ohne Downtime
pm2 reload myapp

Deployment-System

// ecosystem.config.js

module.exports = {
  apps: [{
    name: 'myapp',
    script: './app.js'
  }],

  deploy: {
    production: {
      user: 'deploy',
      host: 'server.example.de',
      ref: 'origin/main',
      repo: 'git@github.com:user/repo.git',
      path: '/var/www/myapp',
      'pre-deploy-local': '',
      'post-deploy': 'npm install && pm2 reload ecosystem.config.js --env production',
      'pre-setup': ''
    }
  }
};
# Erstes Deployment
pm2 deploy production setup

# Deployment
pm2 deploy production

Umgebungsvariablen

In Ecosystem

{
  env: {
    NODE_ENV: 'development',
    API_KEY: 'dev-key'
  },
  env_production: {
    NODE_ENV: 'production',
    API_KEY: 'prod-key'
  },
  env_staging: {
    NODE_ENV: 'staging',
    API_KEY: 'staging-key'
  }
}

Starten mit Environment

pm2 start ecosystem.config.js --env production

Env zur Laufzeit ändern

pm2 restart myapp --update-env

Cluster-Modus

Skalierung

# Auf 4 Instanzen skalieren
pm2 scale myapp 4

# 2 Instanzen hinzufügen
pm2 scale myapp +2

# 1 Instanz entfernen
pm2 scale myapp -1

Load Balancing

// PM2 verteilt automatisch (Round-Robin)
{
  instances: 'max',  // Alle CPUs
  exec_mode: 'cluster'
}

Docker-Integration

Dockerfile

FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .

RUN npm install pm2 -g

EXPOSE 3000

CMD ["pm2-runtime", "ecosystem.config.js"]

pm2-runtime

# Für Container (kein Daemon)
pm2-runtime ecosystem.config.js

Troubleshooting

Probleme debuggen

# Detaillierte Infos
pm2 show myapp

# Logs prüfen
pm2 logs myapp --err

# Prozess beschreiben
pm2 describe myapp

Häufige Probleme

# Prozess startet nicht
# → Pfade prüfen
# → Berechtigungen prüfen
# → node_modules prüfen

# Hoher Memory
pm2 restart myapp --max-memory-restart 500M

# Prozess-Dump löschen
pm2 kill
pm2 resurrect  # oder pm2 start ...

Zusammenfassung

| Befehl | Funktion | |--------|----------| | pm2 start | Prozess starten | | pm2 stop | Prozess stoppen | | pm2 restart | Neustart | | pm2 reload | Zero-Downtime Reload | | pm2 delete | Prozess löschen | | pm2 logs | Logs anzeigen | | pm2 monit | Monitoring | | pm2 save | Prozesse speichern |

| Datei | Funktion | |-------|----------| | ecosystem.config.js | App-Konfiguration | | ~/.pm2/ | PM2-Daten |

| Modus | Verwendung | |-------|------------| | fork | Single-Prozess | | cluster | Multi-Core |

Fazit

PM2 ist der Standard-Prozessmanager für Node.js in Produktion. Der Cluster-Modus nutzt alle CPU-Kerne. Automatische Restarts erhöhen die Verfügbarkeit. Das Deployment-System vereinfacht Rollouts. Zero-Downtime-Reloads sind für Production-Anwendungen essentiell. Mit PM2 Plus gibt es optional ein Cloud-basiertes Dashboard.