问题表现
在 SELinux + Systemd 的 Linux 系统上,用 PM2 管理部署 Node.js, Python 应用时,你会发现 PM2 进程每 1~2 分钟就会被杀死。
https://stackoverflow.com/questions/62814539/pm2-keeps-getting-killed-every-90-seconds-on-centos-8
https://github.com/Unitech/pm2/issues/4813
由于 PM2 本身被杀死了,它管理的所有 Node.js/Python 应用实例也会被连锁杀死。PM2 在被杀死后会重启,因此问题并不容易被发现。你可能会在进程杀死重启的几秒时间窗口偶尔看到一些 502 错误。
根本原因
pm2 startup 命令会创建一个 Systemd 系统服务。这个 Systemd 系统服务会读取 pm2 保存的文件,而这些文件保存的用户目录下面。(默认:/home/your_user/.pm2/) 然而,SELinux 认为这是违规操作,因此拒绝访问,进而导致 Systemd 服务失败并重启。Systemd 会发送 KILL 信号给 PM2,导致 PM2 被杀死然后重启。
解决方案
最简单和安全的解决方案,是修改 SELinux 规则以允许 Systemd 访问 ~/.pm2 目录。
# 1. Define the rule in the SELinux database
sudo semanage fcontext -a -t var_run_t "/home/<your_user>/.pm2(/.*)?"
# 2. Apply the rule to the existing files
sudo restorecon -Rv /home/<your_user>/.pm2
发表回复