系统单元文件中 Wants= 与 WantedBy= 的最佳实践

Kei*_*ith 8 systemd systemd-unit

据我从systemd的文档中可以看出,Wants=WantedBy=执行相同的功能,除了前者放在依赖单元文件中,反之亦然。(那个,并WantedBy=创建unit.type.wants目录并用符号链接填充它。)

来自DigitalOcean:了解系统单位和单位文件

WantedBy=指令...允许您以与Wants=[Unit]部分中的指令类似的方式指定依赖关系。不同之处在于该指令包含在辅助单元中,允许列出的主要单元保持相对清洁。

它真的只是保持单元文件“干净”吗?使用这两个指令的最佳实践是什么?也就是说,如果服务阿尔法“想”的服务测试版,我什么时候应该用Wants=beta.servicealpha.service和什么时候应该更喜欢WantedBy=alpha.servicebeta.service

Pau*_*per 8

功能上

Wants是在Unit节中,WantedBy是在Install.

init 进程systemd根本不处理/使用该Install部分。相反,必须在multi-user.target.wants. 通常,这是由systemctl读取该Install部分的实用程序完成的。

总之,WantedBysystemctl enable/影响systemctl disable

逻辑上

考虑哪些服务应该“知道”或“知道”另一个。例如,一个常见的用法WantedBy

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

或者,可以在 multi-user.target 中:

[Unit]
Wants=nginx.service
Run Code Online (Sandbox Code Playgroud)

但第二种方式没有意义。从逻辑上讲,nginx.service 知道系统定义的 multi-user.target,而不是相反。

所以在你的例子中,如果 alpha 的作者知道 beta,那么 alpha Wantsbeta。如果 beta 的作者知道 alpha,那么 beta 就是WantedByalpha。

为了帮助您做出决定,您可以考虑可以在没有其他服务的情况下安装哪些服务(例如,从包管理器中)。

配置目录

作为您盒子中的另一个工具,知道 systemd 文件也可以使用配置目录进行扩展:/etc/systemd/system/myservice.service.d/extension.conf

This allows you to add dependencies where neither service is originally authored to know about the other. I often use this with mounts, where (for example) neither nginx nor the mount need explicit knowledge of the other, but I as the system adminstrator understand the dependency. So I create nginx.service.d/mymount.conf with Wants=mnt-my.mount.