结合所有收集到的知识(非常感谢Julian Knight的想法)和过去一周测试的方法,我决定接受下面描述的部署解决方案(我想我很乐意分享以帮助其他有类似问题的人):
脚本错误时自动重启和脚本更改时自动重新加载由 forever处理,因为它还包括脚本监视,只要 Forever 是从 node.js 脚本中生成的。
为此,我添加了一个server.js
来启动app.js
我们实际想要运行的脚本:
服务器.js
var forever = require('forever'),
child = new(forever.Monitor)('app.js', {
'silent': false,
'pidFile': 'pids/app.pid',
'watch': true,
'watchDirectory': '.', // Top-level directory to watch from.
'watchIgnoreDotFiles': true, // whether to ignore dot files
'watchIgnorePatterns': [], // array of glob patterns to ignore, merged with contents of watchDirectory + '/.foreverignore' file
'logFile': 'logs/forever.log', // Path to log output from forever process (when daemonized)
'outFile': 'logs/forever.out', // Path to log output from child stdout
'errFile': 'logs/forever.err'
});
child.start();
forever.startServer(child);
这将监视应用程序目录中的所有文件的更改,并在更改后forever
立即重新启动正在运行的脚本。由于日志和 pidfile 位于应用程序的子目录中,因此必须从文件监视中忽略它们,否则脚本将循环重新启动:
.foreverignore
pids/**
logs/**
为了让这一切在系统启动时开始,使我们能够start node-app
使用stop node-app
Ubuntu的 Upstart轻松控制服务。我将两个示例(这个和这个)组合成一个可以很好地完成工作的示例:
/etc/init/node-app.conf
# This is an upstart (http://upstart.ubuntu.com/) script
# to run the node.js server on system boot and make it
# manageable with commands such as
# 'start node-app' and 'stop node-app'
#
# This script is to be placed in /etc/init to work with upstart.
#
# Internally the 'initctl' command is used to manage:
# initctl help
# initctl status node-app
# initctl reload node-app
# initctl start node-app
description "node.js forever server for node-app"
author "Remco Overdijk <remco@maxserv.nl>"
version "1.0"
expect fork
# used to be: start on startup
# until we found some mounts weren't ready yet while booting:
start on started mountall
stop on shutdown
# Automatically Respawn:
respawn
respawn limit 99 5
env HOME=/home/user/node-app-dir
script
# Not sure why $HOME is needed, but we found that it is:
export HOME=$HOME
chdir $HOME
exec /usr/local/bin/node server.js > logs/node.log &
end script
#post-start script
# # Optionally put a script here that will notifiy you node has (re)started
# # /root/bin/hoptoad.sh "node.js has started!"
#end script
正如Kevin 在他的文章中明智地提到,以 root 身份运行 node 是不明智的,因此我们将exec sudo -u www-data /usr/local/bin/node
在下周迁移到新服务器时将其更改。
因此,它forever
会自动node server.js
启动,由 启动upstart
,并监控崩溃和文件更改,让整个设置运行只要我们想要的时间。
我希望这对任何人都有帮助。