优雅关闭consul
consul关闭原理分析
consul agent 在正常关闭的时候会向集群发送 leave 信令,宣告自己离开集群,那么什么才叫正常关闭呢?
首先 agent 监听了三个系统信令,os.Interrupt, syscall.SIGTERM, syscall.SIGHUP
os.Interrupt, syscall.SIGTERM两个信令分开处理,
os.Interrupt
这个信令对应的其实就是 ctrl+c, 这一般是我们在开发时才会用到,那么和这个信令配合的配置是*config.SkipLeaveOnInt ,这个配置项不配置,默认就是 false, 那么
sig == os.Interrupt && !(*config.SkipLeaveOnInt)
就为 true, 接着就会执行 leave信令,这完全适用于我们在开发环境中,使用自己开发电脑上的 consul agent, 退出就自动注销,不用怕收到报警.
syscall.SIGTERM
这个信令一般我们执行
kill -15 ${pid}
就会发送,当然kill ${pid}
默认就是发送15号信令,这个信令配合config.LeaveOnTerm配置项来处理是否发送 leave 信令,这种一般是 agent 在后台运行时才会用到的,这种情况大家都知道主要场景是在生产环境,如果配置config.LeaveOnTerm= true 的话,那么停机维护的时候,也收不到烦人的报警.贴心吧
在前台运行的情况下:
ctrl+c +最简化配置即可正常关闭,
在后台运行的情况下:
配置中指定
LeaveOnTerm: true
,维护时,使用kill -15 ${pid}
来关闭进程,即可正常关闭掉 node, 并注销成功.
官方参数说明
leave_on_terminate
If enabled, when the agent receives a TERM signal, it will send aLeave
message to the rest of the cluster and gracefully leave. The default behavior for this feature varies based on whether or not the agent is running as a client or a server (prior to Consul 0.7 the default value was unconditionally set tofalse
). On agents in client-mode, this defaults totrue
and for agents in server-mode, this defaults tofalse
.
配置修改
在/data/consul_conf目录创建配置文件
conf.json
{
"leave_on_terminate": true
}
修改启动参数,通过参数“-config-dir”指定配置文件目录
nohup consul agent -data-dir=/data/consul_data -config-dir=/data/consul_conf -datacenter=shenzhen -join 10.0.0.11 >> /data/logs/consul.log 2>&1 &