为什么运行Node.js应用程序的systemd服务在正确停止时会显示失败状态?

时间:2014-08-04 04:47:46

标签: node.js coffeescript ansible systemd

我有一个运行Node.js应用程序的systemd服务文件。该服务似乎运行良好,但当我停止服务时,使用systemctl stop train服务进入失败状态。

[root@localhost portaj]# systemctl stop train
[root@localhost portaj]# systemctl status train
train.service - Train Service
   Loaded: loaded (/etc/systemd/system/train.service; enabled)
   Active: failed (Result: exit-code) since Mon 2014-08-04 04:40:17 UTC; 1s ago
  Process: 25706 ExecStart=/opt/node/bin/node /opt/train/src/server/start.js (code=exited, status=143)
 Main PID: 25706 (code=exited, status=143)

Aug 04 04:33:39 localhost.localdomain train[25706]: Train Server listening on port 3000
Aug 04 04:40:17 localhost.localdomain systemd[1]: Stopping Train Service...
Aug 04 04:40:17 localhost.localdomain systemd[1]: train.service: main process exited, code=exit.../a
Aug 04 04:40:17 localhost.localdomain systemd[1]: Stopped Train Service.
Aug 04 04:40:17 localhost.localdomain systemd[1]: Unit train.service entered failed state.

我的服务文件如下所示:

[Unit]
Description=Train Service
After=network.target

[Service]
Environment=PORT=4000
Environment=NODE_ENV=development
ExecStart=/opt/node/bin/node /opt/train/src/server/start.js
Restart=on-failure
SyslogIdentifier=train

[Install]
WantedBy=network.target

我怀疑Node.js应用程序正在返回systemd认为失败的状态代码。我不确定是否需要让我的Node.js应用程序返回不同的状态代码,如果可能的话。或者,如果我需要修改systemd服务文件以某种方式采取不同的行为。

如果有帮助,部署脚本就在这里:https://github.com/JonathanPorta/ansible-train

实际的Node.js应用程序在这里: https://github.com/JonathanPorta/train

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:7)

默认情况下,当使用SIGINT终止时, node.js 将退出,状态代码为143.即128+SIGTERM。这是预期的行为。来自doc:

  

SIGTERM和SIGINT在非Windows平台上具有默认处理程序   在退出代码128 +信号编号之前重置终端模式。   如果其中一个信号安装了侦听器,则为默认值   行为将被删除(节点将不再退出)。

如果要优雅地退出,则必须override the default signal handler

process.on('SIGTERM', function() {
    console.log('SIGTERM')
    // do whatever to terminate properly
    // at worst, just 'exit(0)'
    process.exit(0)
});

process.on('SIGINT', function() {
    console.log('SIGINT')
    // do whatever to terminate properly
    // at worst, just 'exit(0)'
    process.exit(0)
});

答案 1 :(得分:2)

您可以在服务单位文件中指定自定义合法退出状态:     SuccessExitStatus = 143