您首先需要以正确的方式安装 Node。我写了一篇关于它的教程:How to get Node 6.7.0 on Linux(当然你可以使用更新的版本,只需在命令中更改版本即可)。
基本上是这样的 - 将版本更改为您喜欢的版本:
# change dir to your home:
cd ~
# download the source:
curl -O https://nodejs.org/dist/v6.1.0/node-v6.1.0.tar.gz
# extract the archive:
tar xzvf node-v6.1.0.tar.gz
# go into the extracted dir:
cd node-v6.1.0
# configure for installation:
./configure --prefix=/opt/node-v6.1.0
# build and test:
make && make test
# install:
sudo make install
# make a symlink to that version:
sudo ln -svf /opt/node-v6.1.0 /opt/node
我建议从源代码构建 Node 并始终运行 make test,但您也可以安装更快的二进制包 - 如果这样做,请确保您了解路径和 hashbang 行的问题 - 更多信息和更多my tutorial 中描述了安装选项。
那么你需要确保每次服务器重启时你的应用程序都启动了。如果可以,我建议使用 Upstart。
使用 Upstart,在 /etc/init/YOURAPP.conf 中保存这样的内容:
# When to start the service
start on runlevel [2345]
# When to stop the service
stop on runlevel [06]
# If the process quits unexpectadly trigger a respawn
respawn
# Start the process
exec start-stop-daemon --start --chuid node --make-pidfile --pidfile /www/YOURAPP/run/node-upstart.pid --exec /opt/node/bin/node -- /www/YOURAPP/app/app.js >> /www/YOURAPP/log/node-upstart.log 2>&1
只是改变:
-
YOURAPP你自己的应用的名字
-
/opt/node/bin/node 通往node 的路径
-
/www/YOURAPP/app/app.js 指向您的 Node 应用程序路径
-
/www/YOURAPP/run 到你想要你的 PID 文件的地方
-
/www/YOURAPP/log 到你想要你的日志的地方
-
--chuid node 到 --chuid OTHERUSER 如果您希望它以不同于 node 的用户身份运行
(确保添加名称来自上述--chuid 的用户)
使用您的/etc/init/YOURAPP.conf,您可以安全地重新启动服务器并让您的应用程序仍在运行,您可以运行:
start YOURAPP
restart YOURAPP
stop YOURAPP
启动、重新启动和停止您的应用 - 这也会在系统启动或关闭期间自动发生。
有关更多信息,请参阅以下答案:
您也可以使用 systemd,但 there are some differences 因为系统是 much more complicated 并且通常会导致 some problems。