更新时间:2023-02-08 18:32:42
从 请注意,如果您不熟悉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).