#!/bin/bash

docker -v

#私有库url
repositryUrl='192.168.7.52:5000'

#获取项目版本号作为镜像的tag
version=`awk '/<version>[^<]+<\/version>/{gsub(/<version>|<\/version>/,"",$1);print $1;exit;}' pom.xml`

#获取小写项目名作为镜像名
typeset -l imageName
imageName=`awk '/<artifactId>[^<]+<\/artifactId>/{gsub(/<artifactId>|<\/artifactId>/,"",$1);print $1;exit;}' pom.xml`  

#批量删除以前构建的镜像

#有些打了tag的镜像和源镜像的imageId相同,需要先根据 repositry:tag删
removelist=$(docker images |grep $imageName | awk '{print $1":"$2}')

if [ ! -n "$removelist" ]; then
echo "nothing to remove"
else
docker rmi $removelist
fi

#再根据ImageId 删
removelist=$(docker images |grep $imageName | awk '{print $3}')

if [ ! -n "$removelist" ]; then
echo "nothing to remove"
else
docker rmi $removelist
fi

#构建镜像
#target/ 为dockerfile所在的路径
docker build -t $imageName:$version .

#推送镜像到私有仓库
docker tag $imageName:$version $repositryUrl/$imageName:$version
docker push $repositryUrl/$imageName:$version

echo "push image success.... "

#将该版本镜像作为latest版本并推送到私有仓库
#如果pull时不指定tag,默认pull latest tag
docker tag $imageName:$version $repositryUrl/$imageName 
docker push  $repositryUrl/$imageName

echo "push latest image success .... "
posted on 2021-04-07 11:30  肖建锋  阅读(235)  评论(0编辑  收藏  举报