如何将node.js应用程序作为后台服务运行? [英] How do I run a node.js app as a background service?
问题描述
由于这些年来引起了很多关注,因此我在文章的底部列出了每个平台的最佳解决方案.
原始帖子:
我希望我的node.js服务器在后台运行,即:当我关闭终端时,我希望服务器继续运行.我已经对此进行了Google搜索,并提出了教程,但是它不起作用如预期.因此,我没有使用该守护程序脚本,而是以为我只使用了输出重定向(2>&1 >> file
部分),但这也不会退出-我在终端中出现空白行,就像它在等待输出/错误.>
我也尝试过将进程置于后台,但是一旦关闭终端,进程也会被终止.
那么当我关闭本地计算机时如何使其保持运行状态?
最佳解决方案:
从 请注意,如果您不熟悉Unix: 将您的服务文件复制到 从 启用它以使用 使用 这取自 我们如何在Linux(2018版)上部署节点应用程序 ,其中还包括用于生成AWS/DigitalOcean/Azure CloudConfig来构建Linux/节点服务器(包括 Since this post has gotten a lot of attention over the years, I've listed the top solutions per platform at the bottom of this post. Original post: I want my node.js server to run in the background, i.e.: when I close my terminal I want my server to keep running. I've googled this and came up with this tutorial, however it doesn't work as intended. So instead of using that daemon script, I thought I just used the output redirection (the I've also tried to put the process in the background, but as soon as I close my terminal the process is killed as well. So how can I leave it running when I shut down my local computer? Top solutions:[Unit]
Description=My app
[Service]
ExecStart=/var/www/myapp/app.js
Restart=always
User=nobody
# Note Debian/Ubuntu uses 'nogroup', RHEL/Fedora uses 'nobody'
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/myapp
[Install]
WantedBy=multi-user.target
/var/www/myapp/app.js
的第一行应带有#!/usr/bin/env node
./etc/systemd/system
. systemctl start myapp
开始. systemctl enable myapp
在启动时运行.journalctl -u myapp
.service
文件)的命令.
2>&1 >> file
part), but this too does not exit - I get a blank line in my terminal, like it's waiting for output/errors.
Copying my own answer from How do I run a Node.js application as its own process?
2015 answer: nearly every Linux distro comes with systemd, which means forever, monit, PM2, etc are no longer necessary - your OS already handles these tasks.
Make a myapp.service
file (replacing 'myapp' with your app's name, obviously):
[Unit]
Description=My app
[Service]
ExecStart=/var/www/myapp/app.js
Restart=always
User=nobody
# Note Debian/Ubuntu uses 'nogroup', RHEL/Fedora uses 'nobody'
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/myapp
[Install]
WantedBy=multi-user.target
Note if you're new to Unix: /var/www/myapp/app.js
should have #!/usr/bin/env node
on the very first line.
Copy your service file into the /etc/systemd/system
.
Start it with systemctl start myapp
.
Enable it to run on boot with systemctl enable myapp
.
See logs with journalctl -u myapp
This is taken from How we deploy node apps on Linux, 2018 edition, which also includes commands to generate an AWS/DigitalOcean/Azure CloudConfig to build Linux/node servers (including the .service
file).
这篇关于如何将node.js应用程序作为后台服务运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!