linux

linux systemd 多种启动方案

背景

此篇文章以nginx服务为例,如果检查nginx服务启动异常(一般语法有误),则启动备选方案。

方案一:定义systemd OnFailure参数

查看systemd 关于nginx的配置文件

编辑文件,添加OnFailure参数,如果nginx启动失败,则启动备选服务nginx.failure.service

vim /lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=https://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
OnFailure=nginx.failure.service

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /var/run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /var/run/nginx.pid)"

[Install]
WantedBy=multi-user.target

创建服务nginx.failure.service

vim /lib/systemd/system/nginx.failure.service

[Unit]
Description=nginx backup


[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.bak.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /var/run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /var/run/nginx.pid)"

[Install]
WantedBy=multi-user.target

重新加载systemd服务

systemctl daemon-reload

方案二:自定义启动shell

查看systemd 关于nginx的配置文件

编辑文件,修改ExecStart启动命令

vim /lib/systemd/system/nginx.service

[Unit]
Description=nginx - high performance web server
Documentation=https://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
#ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecStart=/bin/sh -c '/usr/sbin/nginx -t &&  /usr/sbin/nginx -c /etc/nginx/nginx.conf  || /usr/sbin/nginx -c /etc/nginx/nginx.bak.conf'
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /var/run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /var/run/nginx.pid)"

[Install]
WantedBy=multi-user.target

ExecStart启动命令介绍
第一步:检查nginx语法/usr/sbin/nginx -t(默认检查/etc/nginx/nginx.conf)
第二步:nginx语法检查通过,则启动/usr/sbin/nginx -c /etc/nginx/nginx.conf
第三步:nginx语法检查不通过,则启动/usr/sbin/nginx -c /etc/nginx/nginx.bak.conf

重新加载systemd服务

systemctl daemon-reload

留言

您的电子邮箱地址不会被公开。 必填项已用 * 标注