Skip to main content

[shell] Docker 部署脚本模板2

#!/bin/bash

if [ $1 == "" ];then
     echo "plsese input the image name of the jar api"
     exit 0
fi

IMAGE=$1 
echo "input image is ${IMAGE}"






######################## delete the container of this jar api  ########################

CONTAINERID=`docker ps -a|grep ${IMAGE} |awk '{print $1}'`
echo "contained id is ${CONTAINERID}"

docker stop ${CONTAINERID}
docker rm ${CONTAINERID}

########################  get image name and image tag ....sed -n 为获取第几行数据  ########################


IMAGENAME=`echo ${IMAGE} | awk -F ":" '{print $1}'`
echo "imagename is ${IMAGENAME}"

IMAGETAG=`echo ${IMAGE}| awk -F ":" '{print $2}'`
echo "imagetag is ${IMAGETAG}"

IMAGEROWNUM=`docker images | grep ${IMAGENAME}| wc -l`
echo "imagerownum is ${IMAGEROWNUM}"

########################  同一镜像名称可能有多个不同的版本,如果同时满足所要删除的镜像名称和tag,则删除该镜像 ########################
for ((i=1;i<=$IMAGEROWNUM;i++))
  do
    echo "i is ${i}"
    IMAGENAME2=`docker images|grep ${IMAGENAME} | sed -n "${i}p" |awk '{print $1}'`
    echo "imagename2 is ${IMAGENAME2}"
    if [ "${IMAGENAME2}" == "${IMAGENAME}" ];then
    IMAGETAG2=`docker images|grep ${IMAGENAME} | sed -n "${i}p" |awk '{print $2}'`
    echo "imagetag2 is ${IMAGETAG2}"
       if [ "${IMAGETAG2}" == "${IMAGETAG}" ];then
       IMAGEID=`docker images|grep ${IMAGENAME} | sed -n "${i}p" |awk '{print $3}'`
       echo "imageid is ${IMAGEID}"

       docker rmi ${IMAGEID}
       fi
    fi
done


######################## 创建镜像  ########################

docker build -t ${IMAGE} . 

######################## 生成容器,并在后台运行,生成容器时才会执行dockerfile文件中的java -jar等指令  ########################

docker run -d --net=host -v /home/xjjtuser/dataAnalysis-logs/:/data-analysis/  -v /home/xjjtuser/docker-program/config/:/config/ --name data-analysis  ${IMAGE}

# 显示日志信息
containerid_new=`docker ps -a | grep ${IMAGE}| awk '{print $1}'`
echo "containerid_new is ${containerid_new}"

docker logs "${containerid_new}"