如何在依赖项升级时重新启动我的 systemd 服务

如何在依赖项升级时重新启动我的 systemd 服务

我编写了一个使用 Postgres 数据库的程序,并为其编写了一个 systemd 服务文件。目前,我的服务在启动时启动得很好,当 Postgres 停止升级时(由apt upgrade),它就会停止。但是,当升级完成并再次启动 Postgres 时,我的服务不会自动启动。

我可以定义一些依赖项来自动重新启动我的服务吗?

这是我的服务在 Postgres 升级期间自动停止后的状态:

● tabill.service - My service
   Loaded: loaded (/srv/tabill/tabill.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Tue 2017-07-04 00:29:24 EEST; 44min ago
 Main PID: 1048 (code=killed, signal=TERM)

请注意,我可以再次手动启动该服务。

这是我的服务文件:

[Unit]
Description=My service
Wants=nginx.service
Requires=postgresql.service
After=postgresql.service

[Service]
Type=simple
ExecStart=/srv/tabill/app/serve
Restart=always
TimeoutSec=60

[Install]
WantedBy=multi-user.target

我尝试添加PartOf=postgresql.serviceBindsTo=postgresql.service,然后手动停止和启动 Postgres,但都没有帮助。

当然,我可以删除Requires,但最好同时停止这两个服务,只要它们都能重新启动即可。

答案1

我找到了答案:我需要将服务文件的最后一行更改为:

WantedBy=postgresql.service

这样,每当 Postgres 启动时,我的服务也会启动 - 但如果我的服务失败,Postgres 不会停止。

本节中的指令[Install]仅影响单元的启用和禁用。但当我的服务已经启用时,事情就没那么简单了:

# systemctl enable tabill.service
Failed to execute operation: Too many levels of symbolic links

该错误消息具有误导性。修复它很简单:

# systemctl disable tabill.service
Removed symlink /etc/systemd/system/tabill.service.
Removed symlink /etc/systemd/system/multi-user.target.wants/tabill.service.

# systemctl enable tabill.service
Failed to execute operation: No such file or directory

# systemctl enable /srv/tabill/tabill.service
Created symlink from /etc/systemd/system/postgresql.service.wants/tabill.service to /srv/tabill/tabill.service.
Created symlink from /etc/systemd/system/tabill.service to /srv/tabill/tabill.service.

现在,只要 Postgres 启动,我的服务就会停止和启动。当然,Postgres 会在系统启动时启动。

相关内容