思路

通过systemctl类似生命周期hook一类的功能,在service退出后出发一个动作(触发可执行脚本)

实现

查看配置文件路径

systemctl status docker.service

root@showmebug-dev:/etc/systemd/system# systemctl status docker.service 
● docker.service - Docker Application Container Engine
   Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2022-09-05 16:31:10 CST; 6min ago
     Docs: https://docs.docker.com
 Main PID: 28743 (dockerd)
    Tasks: 19
   Memory: 44.3M
      CPU: 522ms
   CGroup: /system.slice/docker.service
           └─28743 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

修改docker.service文件

vim /lib/systemd/system/docker.service

# /lib/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
BindsTo=containerd.service
After=network-online.target firewalld.service containerd.service
Wants=network-online.target
Requires=docker.socket

[Service]
Type=notify
# the default is not to use systemd for cgroups because the delegate issues still
# exists and systemd currently does not support the cgroup feature set required
# for containers run by docker
ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

ExecReload=/bin/kill -s HUP $MAINPID

#启动前 ExecStartPre=-/bin/sh -c "echo 'docker正在启动 | tee -a /root/messages.txt"
#停止前 ExecStopPre=-/bin/sh -c "echo 'docker正在停止' | tee -a /root/messages.txt"
# 例:启动后通过curl发送企业微信webhook消息
ExecStartPost=-/bin/sh -c "curl -X POST https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxxxx -H 'Content-Type: application/json' -d '{ \"msgtype\": \"markdown\", \"markdown\": { \"content\": \"**Docker**(%n) has <font color="info">started</font> on `%H`\"} }'"
# 例:停止后通过curl发送企业微信webhook消息
ExecStopPost=-/bin/sh -c "curl -X POST https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxxxx -H 'Content-Type: application/json' -d '{ \"msgtype\": \"markdown\", \"markdown\": { \"content\": \"**Docker**(%n) has <font color="warning">stoped</font> on `%H`\"} }'"

# 省略……

systemd.unit

systemd.service配置文件中可使用的说明符(变量)

加载新配置文件

systemctl daemon-reload

验证效果

# 可以另外开一个终端tail -f /root/messages.txt,然后重启docker.service来验证
systemctl restart docker.service 

企业微信推送效果

企业微信推送效果

参考

systemd.service

Scaledrone realtime messaging service - Blog

How to send an email if a systemd service is restarted?

文章作者: Administrator
本文链接:
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 if(xyz!=null)
技术分享 Linux
喜欢就支持一下吧
打赏
微信 微信
支付宝 支付宝