我创建了一个 Linux 服务来在服务器(重新)启动时启动 shell 脚本。在测试我的服务器时,我发现该服务能够在我手动启动时启动,但在使用“systemctl”启用它时无法启动。是什么原因造成的?
我的日志:
systemctl 状态脚本.服务
script.service - name
Loaded: loaded (/etc/systemd/system/scriptname.service; enabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Mon 2024-03-04 15:39:34 CET; 3min 45s ago
Process: 1303 ExecStart=/usr/local/bin/scriptname.sh (code=exited, status=126)
Main PID: 1303 (code=exited, status=126)
Mar 04 15:39:34 sar systemd[1]: Started ######.
Mar 04 15:39:34 sar systemd[1]: scriptname.service: main process exited, code=exited, status=126/n/a
Mar 04 15:39:34 sar systemd[1]: Unit scriptname.service entered failed state.
Mar 04 15:39:34 sar systemd[1]: scriptname.service failed.
Journalctl -u 服务名称.服务 |尾部-n 50
-- Reboot --
Mar 04 15:39:34 sar systemd[1]: Started #####.
Mar 04 15:39:34 sar systemd[1]: scriptname.service: main process exited, code=exited, status=126/n/a
Mar 04 15:39:34 sar systemd[1]: Unit scriptname.service entered failed state.
Mar 04 15:39:34 sar systemd[1]: scriptname.service failed.
答案1
这是解决方案:
对服务文件进行以下更改解决了我的问题:
- 添加
Group
,Restart
和WantedBy
行,它应该可以正常启动。 - 将组 ID 更改为您自己的用户的 ID。
vi /etc/systemd/system/servicename.service
[Unit]
Description= app description
After=network.target
Wants=network-online.target #(optional)
[Service]
Type=simple
User=t9s1takuser
Group=208816585
ExecStart=/usr/local/bin/myscript.sh
Restart=on-failure
[Install]
WantedBy=multi-user.target