systemd templated unit 是 systemd 提供的一种强大功能,允许用户创建可重用且参数化的服务单元文件。通过使用模板语法(通常是使用“@”符号),可以定义一个通用的服务单元,然后在启动时传递不同的参数,从而实例化多个服务实例。
以 sing-box 为例,假设我们有一个名为 sing-box@.service 的模板单元文件,其内容如下:
root@coal-cloud:~ # cat /etc/systemd/system/sing-box@.service
[Unit]
Description=sing-box (%i)
After=network.target
[Service]
WorkingDirectory=/opt/sing-box/sing-box-1.11.14-linux-amd64
ExecStart=/opt/sing-box/sing-box-1.11.14-linux-amd64/sing-box run -c /opt/sing-box/sing-box-1.11.14-linux-amd64/%i.json
Restart=on-failure
LimitNOFILE=1048576
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
此时,通过传递不同的实例名称来启动多个 sing-box 服务,每个实例即使用不同的配置文件,例如在 /opt/sing-box/sing-box-1.11.14-linux-amd64/ 目录下的 8080.json,然后启动服务:
systemctl enable --now sing-box@8080
检查服务状态:
systemctl status sing-box@8080
会发现服务已经成功启动,并且使用了指定的配置文件 8080.json。这种方式使得管理多个类似服务变得非常方便和高效。