创建在屏幕内运行 node.js 应用程序的脚本,以便 systemctl 作为服务启动

创建在屏幕内运行 node.js 应用程序的脚本,以便 systemctl 作为服务启动

我有一个 node.js 应用程序,我想将其设置为启动时启动的服务。

我可以使用 systemctl 通过在 /etc/systemd/system/TestApp.service 中创建脚本来做到这一点。

问题是我希望这个应用程序在屏幕内运行,因此我可以通过登录系统并发出诸如 screen -r -D TestApp 之类的命令来附加它

但这样做会导致 sysmtemctl 失败并且应用程序无法启动。

这是我创建的脚本:

[Unit]
Description=Script to start TestApp website on bootup

[Service]
ExecStart=/usr/bin/screen -S TestApp "/usr/bin/node  /opt/NodeApps/TestApp/mainApp.js"

[Install]
WantedBy=multi-user.target

这是 systemctl 的状态及其引发的错误:

sudo systemctl status TestApp.service 
TestApp.service - Script to start TestApp website on bootup
   Loaded: loaded (/etc/systemd/system/TestApp.service; disabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Sun 2020-09-13 09:35:21 UTC; 30s ago
 Main PID: 13012 (code=exited, status=1/FAILURE)

Sep 13 09:35:21 sp-webserver systemd[1]: Started Script to start TestApp website on bootup.
Sep 13 09:35:21 sp-webserver screen[13012]: Must be connected to a terminal.
Sep 13 09:35:21 sp-webserver systemd[1]: TestApp.service: Main process exited, code=exited, status=1/FAILURE
Sep 13 09:35:21 sp-webserver systemd[1]: TestApp.service: Failed with result 'exit-code'.

请建议如何最好地设置它,以便它在启动时在屏幕内运行。

答案1

我最终自己排除了故障并解决了问题。这是解决方案:

创建文件 /etc/systemd/system/TestApp.service

[Unit]
Description=Script to start TestApp website on bootup

# Listed below are three [Service] sections, we need only one of them. These three list our three different ways we can do this.
All three sections will start the processes as non root user 'testuser'. If we want them to start the processes as root, then we'd say User=root OR User="root" (not sure which one)

# The service section without the use of screen.
[Service]
WorkingDirectory=/opt/NodeApps/TestApp
ExecStart=/usr/bin/node /opt/NodeApps/TestApp/mainApp.js
Restart=always
RestartSec=3
User=testuser

# The service section with the use of screen as separate process, i.e. node will start inside screen, but  top will show screen and node as separate processes
[Service]
Type=forking
WorkingDirectory=/opt/NodeApps/TestApp
ExecStartPre=/usr/bin/screen -dmS TestApp
ExecStart=/usr/bin/node /opt/NodeApps/TestApp/mainApp.js
Restart=always
RestartSec=3
User=testuser

# The service section with the use of screen i.e. node will start inside screen, and top will show screen  as a process (node does not get a separate pid) 
[Service]
Type=forking
WorkingDirectory=/opt/NodeApps/TestApp
ExecStart=/usr/bin/screen -dmS TestApp /usr/bin/node /opt/NodeApps/TestApp/mainApp.js
Restart=always
RestartSec=3
User=testuser

[Install]
WantedBy=multi-user.target 

保存此文件后,请执行以下操作:

  1. 取得该文件的所有权。 ( 须藤 chown )
  2. 将权限设置为 644,因此它不可执行( chmod 644 )

使用如下命令测试它:

sudo systemctl start TestApp.service
sudo systemctl stop TestApp.service
sudo systemctl status TestApp.service

一旦满意,像这样启用它,这样它就会在启动时执行:

sudo systemctl enable TestApp.service

相关内容