#操作/项目路径(Dockerfile存放的路劲)
BASE_PATH=/Users/michael/Gaia/DevOps/jenkins-work-space
# 源jar路径
SOURCE_PATH=/Users/michael/.jenkins/workspace
#docker 镜像/容器名字或者jar名字 这里都命名为这个
SERVER_NAME=jenkins-demo
#容器id
CID=$(docker ps -a | grep "$SERVER_NAME" | awk '{print $1}')
#镜像id
IID=$(docker images | grep "$SERVER_NAME" | awk '{print $3}')
DATE=`date +%Y%m%d%H%M`
# 最新构建代码 移动到项目环境
function transfer(){
echo "最新构建代码$SOURCE_PATH/$SERVER_NAME/target/$SERVER_NAME.jar.迁移至$BASE_PATH...."
cp $SOURCE_PATH/$SERVER_NAME/target/$SERVER_NAME.jar $BASE_PATH
echo "迁移完成"
}
# 备份
function backup(){
if [ -f "$BASE_PATH/$SERVER_NAME.jar" ]; then
echo "$SERVER_NAME.jar备份..."
cp $BASE_PATH/$SERVER_NAME.jar $BASE_PATH/backup/$SERVER_NAME-$DATE.jar
echo "备份$SERVER_NAME.jar完成"
else
echo "$BASE_PATH/$SERVER_NAME.jar不存在,跳过备份"
fi
}
# 构建docker镜像
function build(){
# 如果容器已经启动则停止,并且删除容器
if [ -n "$CID" ]; then
echo "存在$SERVER_NAME容器正在运行中,CID=$CID"
docker stop $CID
echo "已停止$SERVER_NAME容器,CID=$CID"
docker rm $CID
echo "已删除$SERVER_NAME容器,CID=$CID容器"
fi
# 如果存在镜像则删除,然后重新构建.如果不存在镜像,则新创建镜像
if [ -n "$IID" ]; then
docker rmi $IID
echo "存在$SERVER_NAME镜像,IID=$IID,已删除."
cd $BASE_PATH
docker build -t $SERVER_NAME .
echo "存在$SERVER_NAME镜像,IID=$IID 已重新构造完成."
else
echo "不存在$SERVER_NAME镜像,开始构建镜像"
cd $BASE_PATH
docker build -t $SERVER_NAME .
fi
}
# 运行docker容器
function run(){
backup
transfer
build
docker run --name $SERVER_NAME -d -p 8091:8091 $SERVER_NAME
echo "$SERVER_NAME容器创建完成"
# 容器直接全部重启
#if [ -n "$CID" ]; then
# echo "存在$SERVER_NAME容器,CID=$CID,重启docker容器 ..."
# docker restart $SERVER_NAME
# echo "$SERVER_NAME容器重启完成"
#else
# echo "不存在$SERVER_NAME容器,docker run创建容器..."
# docker run --name $SERVER_NAME -d -p 8091:8091 $SERVER_NAME
# echo "$SERVER_NAME容器创建完成"
#fi
}
#入口
run