这是一个老问题,但在 Google 上排名很高。我几乎不敢相信投票最高的答案,因为在屏幕会话中运行 node.js 进程,使用 & 甚至使用 nohup 标志——所有这些——只是解决方法。
特别是 screen/tmux 解决方案,它确实应该被视为 业余 解决方案。 Screen 和 Tmux 并不是为了让进程保持运行,而是为了多路复用终端会话。很好,当您在服务器上运行脚本并想要断开连接时。但是对于 node.js 服务器,您不希望您的进程附加到终端会话。这太脆弱了。 要保持运行,您需要守护进程!
有很多好工具可以做到这一点。
PM2:http://pm2.keymetrics.io/
# basic usage
$ npm install pm2 -g
$ pm2 start server.js
# you can even define how many processes you want in cluster mode:
$ pm2 start server.js -i 4
# you can start various processes, with complex startup settings
# using an ecosystem.json file (with env variables, custom args, etc):
$ pm2 start ecosystem.json
我看到支持 PM2 的一大优势是它可以生成系统启动脚本以使进程在重新启动之间持续存在:
$ pm2 startup [platform]
platform 可以是ubuntu|centos|redhat|gentoo|systemd|darwin|amazon。
forever.js:https://github.com/foreverjs/forever
# basic usage
$ npm install forever -g
$ forever start app.js
# you can run from a json configuration as well, for
# more complex environments or multi-apps
$ forever start development.json
初始化脚本:
我不会详细介绍如何编写初始化脚本,因为我不是这个主题的专家,这个答案太长了,但基本上它们是简单的 shell 脚本,由操作系统触发事件。你可以阅读更多关于这个here
Docker:
只需在带有-d 选项的 Docker 容器中运行您的服务器,瞧,您就有了一个守护进程的 node.js 服务器!
这是一个示例 Dockerfile(来自 node.js official guide):
FROM node:argon
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY . /usr/src/app
EXPOSE 8080
CMD [ "npm", "start" ]
然后构建你的镜像并运行你的容器:
$ docker build -t <your username>/node-web-app .
$ docker run -p 49160:8080 -d <your username>/node-web-app
希望这有助于有人登陆此页面。始终使用合适的工具完成工作。它会为您省去很多麻烦和几个小时!