我在 Ubuntu Server(14.04 LTS)上运行一个使用 Node.JS 的网站。重启机器后,我当前的工作流程是通过运行以下命令手动启动服务器
$ forever start app.js
我现在正尝试使用 Upstart 来自动化这个过程。我曾经使用过查配置我以前在 RHEL 上用过,但我对 Upstart 还不熟悉。我写了以下脚本并将其保存在/etc/init/myapp.conf。
#!upstart
description "Start the node process with Upstart"
start on startup
stop on shutdown
expect fork
env APP_DIR="/path/to/app"
env NODE_BIN="/usr/local/bin"
env HOME_DIR="/home/admin"
script
date
echo "Starting"
su admin
cd $APP_DIR
PATH=$NODE_BIN:$PATH
HOME=$HOME_DIR
echo "Running forever start"
forever start app.js
end script
pre-stop script
date
echo "Stopping"
su admin
cd $APP_DIR
PATH=$NODE_BIN:$PATH
HOME=$HOME_DIR
echo "Running forever stop"
forever stop app.js
end script
但是,该脚本似乎不起作用。当我运行sudo start myapp
或 时sudo stop myapp
,控制台就挂起了。
我希望 Upstart 尽可能地模拟我刚刚登录计算机后重新启动并运行时发生的情况forever start app.js
,包括运行该过程的用户、默认日志文件位置等等。
有任何想法吗?
答案1
通过使用,upstart
您将能够停止使用forever
节点进程管理。upstart 具有确保在发生故障(或几乎任何其他事件)时启动/停止/重新启动您的进程的机制
这里是 upstart 脚本的修改版本,它使用 upstart 的respawn
指令来处理在进程崩溃时重新启动进程:
description "Start the node process with Upstart"
author "you"
# use if your process is going to fork *once*
# expect fork
# use if your process is going to fork *twice*
# exepect daemon
# respawn the process indefinitely
# (ie. disregard the number of times it crashed
# during a given interval and continuously
# restart the process)
respawn
respawn limit unlimited
setuid admin
# ensures the process is only started once we have
# filesystem access and an ethernet interface other
# than loopback is available (ie. internet conn)
# if your node process doesn't require net connectivity
# just remove the `and net-device-up...`
start on (local-filesystem and net-device-up IFACE!=lo)
stop on shutdown
# chdir sets the directory for all script blocks
# (pre/post/errethang)
chdir "/path/to/your/app"
script
# we're already in /path/to/your/app cause of `chdir`
echo "app is starting"
/usr/local/bin/node app.js 2>&1 > app.log
end script
pre-stop script
echo "app is about to stop"
end script
最后,为了确保服务配置中没有语法错误,您可以使用init-checkconf /etc/init/myapp.conf
。
我对 upstart 的主要参考资料是这里. 不过,这份文档有点太重了。并且很难从一些例子中辨别出现实世界的用法。