#!/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