在最近的毕业设计中,由于项目使用了Docker容器,每次重新启动虚拟机的时候都要将每个容器一个一个的去启动,但经过一段时间之后已经厌倦了这一过程,因此参考各个博客的资料,自己编写了批量启动和停止容器的shell脚本。
1.批量启动
#!/bin/bash
containerNames="laf-mysql laf-nacos laf-mq laf-es kibana"
statusLived="live"
statusdead="Dead"
notExistContainer="None"
retryCount=3
function GetContainerStatus(){
containerExist=$(sudo docker ps -a | grep -i $1 | wc -l )
if [ ${containerExist} -gt 0 ]
then
pid=$(sudo docker stats --format "{{.PIDs}}" --no-stream $1 )
if [ "${pid}" != "0" ]
then
echo "${statusLived}"
else
echo "${statusdead}"
fi
else
echo "${notExistContainer}"
fi
}
function StartContainer(){
sudo docker restart $1
}
for containerName in ${containerNames}
do
for((i=1;i<=${retryCount};i++))
do
status=$(GetContainerStatus ${containerName} )
echo "Container ${containerName} status is ${status}"
if [ "${status}" == ${statusLived} ]
then
echo "Container ${containerName} already running"
break
fi
if [ "${status}" == ${notExistContainer} ]
then
echo "Container ${containerName} not existed"
break
fi
if [ "${status}" == ${statusdead} ]
then
echo "Container ${containerName} stopped ,start container"
StartContainer ${containerName}
verifyStatus=$(GetContainerStatus ${containerName} )
if [ "${verifyStatus}" == ${statusLived} ]
then
echo "start container ${containerName} success "
break
else
echo "${i} retry start container"
StartContainer ${containerName}
fi
fi
done
done
使用时将需要批量的容器id(ContainerIds)替换成自己需要批量启动的容器名称即可。
2.批量停止
#!/bin/bash
containerNames="laf-mysql laf-nacos laf-mq laf-es kibana"
statusLived="live"
statusdead="Dead"
notExistContainer="None"
retryCount=3
function GetContainerStatus(){
containerExist=$(sudo docker ps -a | grep -i $1 | wc -l )
if [ ${containerExist} -gt 0 ]
then
pid=$(sudo docker stats --format "{{.PIDs}}" --no-stream $1 )
if [ "${pid}" != "0" ]
then
echo "${statusLived}"
else
echo "${statusdead}"
fi
else
echo "${notExistContainer}"
fi
}
function StopContainer(){
sudo docker stop $1
}
for containerName in ${containerNames}
do
for ((i=1;i<=${retryCount};i++))
do
status=$(GetContainerStatus ${containerName} )
echo "Container ${containerName} status is ${status}"
if [ "${status}" == ${statusdead} ]
then
echo "Container ${containerName} already stopped"
break
fi
if [ "${status}" == ${notExistContainer} ]
then
echo "Container ${containerName} not existed"
break
fi
if [ "${status}" == ${statusLived} ]
then
echo "Container ${containerName} is lived ,stop container"
StopContainer ${containerName}
verifyStatus=$(GetContainerStatus ${containerName} )
if [ "${verifyStatus}" == ${statusdead} ]
then
echo "stop container ${containerName} success "
break
else
echo "${i} retry stop container"
StopContainer ${containerName}
fi
fi
done
done
启动脚本命令:
sh 文件路径/文件名称