PM2 là process manager cho production Node.js — gộp auto-restart, clustering, logging và monitoring vào một công cụ.
js
// ecosystem.config.js — chạy: pm2 start 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 reload apirestart lần lượt từng worker (rolling restart) nên deploy không downtime;pm2 restartgiết hết cùng lúc — deploy thì dùng reload.pm2 monitxem CPU/RAM realtime từng process,pm2 statusxem tổng quan.pm2 logs api --lines 100đọc log,pm2 flushxoá log; ghép với logrotate để khỏi đầy đĩa.pm2 startupsinh script systemd để PM2 tự chạy khi server reboot,pm2 savelưu danh sách process hiện tại.max_memory_restarttự restart khi process vượt ngưỡng RAM — lưới an toàn cho rò rỉ bộ nhớ.
Lưu ý: cluster mode là shared-nothing nên session/cache phải nằm ở Redis; và pm2 reload chỉ mượt khi app có xử lý SIGINT/SIGTERM.