1.需求
公司部署服务,要先判断比如db服务先启动,然后再启动微服务
2.思路
- 兼容容器与非容器架构,原理一样,无需纠结架构,领会精神。
- 去掉docker开机自启,将检测脚本弄成开机自启(写入 /etc/rc.d/rc.local 其中rc.local需要执行权限chmod+x rc.local即可)
- 脚本探测目标服务器的目标端口,探测到端口则启动服务(此处直接控docker本身,docker下的容器都是设置的docker服务起则容器起,所以直接控制docker服务即可)
- 不需要可去掉记录日志功能,直接满足条件启动服务或者执行脚本都可以
3.脚本编码如下
#!/bin/bash
#Date 2023-01-12
#Author dongwn
#Version v0.0.1
#description: auto-start.sh
NACOS_HOST=192.168.1.1
NACOS_PORT=8848
Log_Path=/root/logs
SLEEP_TIME=10
flag=4
at_time=""
at_date=""
getAtTime() {
at_time="$(date +%Y-%m-%d-%H:%M:%S) --- "
at_date=$(date +%Y-%m-%d)
}
autoStartWebService() {
if [ ! -d "$Log_Path" ]; then
mkdir -p $Log_Path
fi
while (($flag < 5)); do
getAtTime
req_message=$(nc -w 1 ${NACOS_HOST} ${NACOS_PORT} </dev/null && echo "200")
getAtTimel
echo $req_message >${Log_Path}/"$at_date"_auto_start.log
if [ -n "$req_message" ]; then
getAtTime
echo "Nacos is running" >>${Log_Path}/"$at_date"_auto_start.log
flag+=1
echo "already-start" >>${Log_Path}/"$at_date"_auto_start.log
systemctl start docker
else
getAtTime
echo "Nacos is not running and please wait for Nacos starting" >>/root/logs/"$at_date"_auto_start.log
sleep $SLEEP_TIME
fi
done
}
autoStartWebService