#!/bin/sh
# jenkins自动打包并上传阿里云服务器
#Jenkins maven打包后路径
DIR="./my-test-service"
#阿里云镜像仓库
WAREHOUSE="java"
#打包项目
PROJECT="my-test-service-prod"
#镜像命名:分支+日期,例:develop_20210810093223
BASIC_TAG=${GIT_BRANCH}_$(date "+%Y%m%d%H%M%S")
RESULT_TAG=${BASIC_TAG##*/}
#docker打包
docker build -t test/$PROJECT:latest $DIR | tee $DIR/Docker_build_result.log
#判断是否打包成功
RESULT=$(cat $DIR/Docker_build_result.log | tail -n 1)
if [["$RESULT" != *Successfully*]];then
exit -1
fi
#docker登录阿里云镜像服务器
docker login --username=username registry.cn-shenzhen.aliyuncs.com --password=password
echo '>>> Add tag to the new image'
docker tag test/$PROJECT:latest registry.cn-shenzhen.aliyuncs.com/$WAREHOUSE/$PROJECT:$RESULT_TAG
echo '>>> Start push new image'
docker push registry.cn-shenzhen.aliyuncs.com/$WAREHOUSE/$PROJECT:$RESULT_TAG
#docker打包并上传完之后删除相应镜像
docker rmi registry.cn-shenzhen.aliyuncs.com/$WAREHOUSE/$PROJECT:$RESULT_TAG
if [ "$(docker ps -qf status=exited)" ];then
docker rm $(docker ps -qf status=exited)
fi
dangling=$(docker images -f "dangling=true" -q)
if [ "$dangling" ];then
docker rmi $dangling
fi
参照各大神后整理并验证,如有侵权,请及时告知!!!