PM2 là production process manager không thể thiếu cho Node.js — cluster mode tận dụng multi-core CPU, pm2 reload cho zero-downtime deploy, max_memory_restart auto-restart khi memory leak.
- PM2 là production process manager cho Node.js — giải quyết auto-restart, clustering, logging, monitoring trong một tool.
- Ecosystem config (
ecosystem.config.js):module.exports = { apps: [{ name: 'api', script: 'dist/index.js', instances: 'max', exec_mode: 'cluster', env: { NODE_ENV: 'production', PORT: 3000 }, max_memory_restart: '500M', error_file: 'logs/err.log', out_file: 'logs/out.log' }] }—pm2 start ecosystem.config.js. - Zero-downtime reload:
pm2 reload apirestart từng worker một (rolling restart), không nhưpm2 restartkill tất cả cùng lúc — dùng reload cho deploys. - Monitoring dashboard:
pm2 monitreal-time CPU/RAM per process;pm2 statusoverview tất cả processes. - Log management:
pm2 logs api --lines 100xem logs;pm2 flushclear logs; tích hợp với logrotate để tránh disk full. - Startup scripts:
pm2 startupgenerate systemd/init script để PM2 tự start khi server reboot;pm2 savelưu current process list.max_memory_restart: tự restart process khi vượt ngưỡng RAM — safety net cho memory leaks. - Lưu ý: PM2 cluster mode dùng shared nothing — sessions/cache phải ở Redis;
pm2 reloadkhông graceful nếu app không handle SIGINT/SIGTERM.
PM2 is an essential production process manager for Node.js — cluster mode exploits multi-core CPUs, pm2 reload enables zero-downtime deploys, and max_memory_restart auto-restarts on memory leaks.
- PM2 is a production process manager for Node.js — providing auto-restart, clustering, logging, and monitoring in a single tool.
- Ecosystem config (
ecosystem.config.js):module.exports = { apps: [{ name: 'api', script: 'dist/index.js', instances: 'max', exec_mode: 'cluster', env: { NODE_ENV: 'production', PORT: 3000 }, max_memory_restart: '500M', error_file: 'logs/err.log', out_file: 'logs/out.log' }] }— start withpm2 start ecosystem.config.js. - Zero-downtime reload:
pm2 reload apirestarts workers one at a time (rolling restart), unlikepm2 restartwhich kills all at once — use reload for deploys. - Monitoring dashboard:
pm2 monitfor real-time CPU/RAM per process;pm2 statusfor an overview of all processes. - Log management:
pm2 logs api --lines 100to view logs;pm2 flushto clear logs; integrate with logrotate to prevent disk from filling. - Startup scripts:
pm2 startupgenerates a systemd/init script so PM2 auto-starts on server reboot;pm2 savesaves the current process list.max_memory_restart: auto-restarts the process when it exceeds a RAM threshold — a safety net for memory leaks.
Pitfall: PM2 cluster mode uses shared-nothing — sessions/cache must be in Redis; pm2 reload is not graceful if the app doesn't handle SIGINT/SIGTERM.