在centos系统中,systemd没有user mode,只有system mode,因此只有root才能执行systemctl enable。如果一个普通用户想把某个服务加入systemd的开机启动,往往需要需要给他sudo的权限。
通过添加target的方法,使得普通用户也能添加开机启动项。譬如需要让用户djf自行添加开机启动项,首先要为他添加一个target。

1. 添加文件 /etc/systemd/system/djf.target

  1. [Unit]
  2. Description=user djf target
  3. [Install]
  4. WantedBy=multi-user.target

2. 创建 /etc/systemd/system/bar.target.wants 文件夹

mkdir /etc/systemd/system/djf.target.wants

image.png

3.添加自定义的servic到 /etc/systemd/system/bar.target.wants 文件夹

image.png

  • service文件中User指定用户djf ```shell

[Unit] Description=prometheus install Documentation=https://prometheus.io/ After=network.target

[Service] Type=simple User=djf Restart=on-failure WorkingDirectory=/home/djf/app//LemingMonitor/prometheus-2.17.1.linux-amd64 ExecStart=/home/djf/app//LemingMonitor/prometheus-2.17.1.linux-amd64/prometheus —web.listen-address=0.0.0.0:9090 —config.file=/home/djf/app//LemingMonitor/prometheus-2.17.1.linux-amd64/prometheus.yml —storage.tsdb.path=/home/djf/app//LemingMonitor/prometheus-2.17.1.linux-amd64/data

[Install] WantedBy=multi-user.target

<a name="pluKz"></a>
# 4. 设置djf.target.wants权限归属用户djf
```shell
chown -R djf:djf /etc/systemd/system/djf.target.wants

5. 使能djf.target

systemctl daemon-reload
systemctl enable djf.target

6. 测试systemctl启停service服务

  • 启动 prometheus

    systemctl start prometheus
    
  • 停止 prometheus

    systemctl stop prometheus
    
  • 重启 prometheus

    systemctl restart prometheus
    
  • 通过ps命令可以查看对应的服务是以用户权限启动

image.png