当然,想要实现无缝重启,kubernetes 算得上是一种很好的解决方案。
不过在开发环境,可能并不会考虑采用 k8s。
如果满足以下 3 点:
- 采用 CI/CD 进行自动构建并自动部署],或者手动上传应用到服务器
- 采用 Docker 进行运行
- 部署过程仅仅是简单上传文件到开发服务器
那么,你就可以考虑以下方式实现自动重启 Docker 容器。
虽然笨拙,但是简单有效。
Code
#!/bin/sh
if [ $# != 2 ]
then
echo "Please input a filename(fullpath) and a command to be executed when the file changes"
exit 1
fi
filename=$1
if [ ! -f "$1" ]
then
echo "File [$1] was not found"
exit 1
fi
lastModified=$(ls -l $filename)
echo "Last modifiled: $lastModified"
while :
do
modified=$(ls -l $filename)
if [ "$lastModified" != "$modified" ]
then
echo "File was changed"
echo "Executing $2"
echo "Restaring docker container"
$2 # execute the command
lastModified=$modified
fi
echo "File last modifiled: $lastModified"
date
echo "Sleep 10s"
sleep 10
done
思路其实很简单:定时检查指定文件的时间戳是否更改,如果更改则执行重启命令。
Execution
将上述脚本保存为 monitor.sh。
// 参数1: 文件名(全路径)
// 参数2: 当文件上传后,需要执行的命令
nohup ./monitor.sh `pwd`/api.jar "docker restart api-dev" >/dev/null 2>&1&
为了保证这个这个程序能够在后台运行
上述脚本的适用范围可能不广,但在这里还是很奏效的。
原则上可以使用任何语言实现上述功能,但考虑到其简单性及便捷性,最后采用了 shell。