#!/usr/bin/sh
#操做/項目路徑(Dockerfile存放的路勁)
BASE_PATH=/home/dockerJarWorkdir/
# 源jar路徑
SOURCE_PATH=/home/jenkinsJarPackage/
#docker 鏡像/容器名字或者 這裏都命名爲這個
DOCKER_SERVER_NAME=es-0.0.2
#jar名字es-0.0.1-SNAPSHOT
JAR_SERVER_NAME=es-0.0.1-SNAPSHOT
#容器id,正常啓動的容器
CID=$(docker ps | grep "$DOCKER_SERVER_NAME" | awk '{print $1}')
#異常容器ID,異常啓動
ERR_CID_Exited=$(docker ps -a | grep "$DOCKER_SERVER_NAME" |grep "Exited"| awk '{print $1}')
ERR_CID_Created=$(docker ps -a | grep "$DOCKER_SERVER_NAME" |grep "Created"| awk '{print $1}')
#鏡像id
IID=$(docker images | grep "$DOCKER_SERVER_NAME" | awk '{print $3}')
DATE=`date +%Y%m%d%H%M`
# 最新構建代碼 移動到項目環境
function transfer(){
echo "cp $SOURCE_PATH/$JAR_SERVER_NAME/target/$JAR_SERVER_NAME.jar to $BASE_PATH ...."
cp $SOURCE_PATH/$JAR_SERVER_NAME/target/$JAR_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 "$IID" ]; then
echo "存在$DOCKER_SERVER_NAME鏡像,IID=$IID"
else
echo "不存在$DOCKER_SERVER_NAME鏡像,開始構建鏡像"
cd $BASE_PATH
docker build -t ${DOCKER_SERVER_NAME} .
fi
}
# 運行docker容器
function run(){
backup
transfer
build
if [ -n "$CID" ]; then
echo "存在$DOCKER_SERVER_NAME容器,CID=$CID,重啓docker容器 ..."
docker restart $DOCKER_SERVER_NAME
echo "$DOCKER_SERVER_NAME容器重啓完成"
elif [ -n "$ERR_CID_Exited" ]
then
echo "異常存在$DOCKER_SERVER_NAME容器,CID=$ERR_CID_Created,刪除異常容器 從新建立..."
docker stop $ERR_CID_Exited
docker rm $ERR_CID_Exited
elif [ -n "$ERR_CID_Created" ]
then
echo "異常存在$DOCKER_SERVER_NAME容器,CID=$ERR_CID_Created,刪除異常容器 從新建立..."
docker stop $ERR_CID_Created
docker rm $ERR_CID_Created
else
echo "不存在$DOCKER_SERVER_NAMEE容器,docker run建立容器..."
# --name docker-test 容器的名字爲docker-test,最後指定的鏡像名稱,
# -d 容器後臺運行
# -p 3636:3636 指定容器映射的端口和主機對應的端口都爲3636
# -v /work/project/:/work/project/ 將主機的/work/project/目錄掛載到容器的/work/project/ 目錄中(不可少每次本地更新jar包重啓容器便可,不用從新構建鏡像)
# --privileged=true 添加特權privileged啓動的容器,能夠看到不少host上的設備,而且能夠執行mount。
#甚至容許你在docker容器中啓動docker容器。
docker run --name ${DOCKER_SERVER_NAME} -v ${BASE_PATH}:${BASE_PATH} -d -p 8091:8092 ${DOCKER_SERVER_NAME}
#一個鏡像多個容器 將內部8091端口映射到服務8093
#docker run --name ${DOCKER_SERVER_NAME} --privileged=true -v ${BASE_PATH}:${BASE_PATH} -d -p 8091:8092 ${DOCKER_SERVER_NAME}
#docker run --name es-0.0.3 -v /home/dockerJarWorkdir/:/home/dockerJarWorkdir/ -d -p 8093:8091 es-0.0.2
echo "$DOCKER_SERVER_NAME容器建立完成"
fi
}
#入口
run
java