事情的缘由是这样,工作中经常出现多个版本同时开发提交测试的需求。现在是排队部署,比较痛苦。
所以想到Docker+jenkins+nginx来搞这件事。
jenkins在Docker中,需要注意的是nginx配置文件要挂在到jenkins在主机的目录中。
第一次写这么长的脚本,比较挫,凑合着看吧,大致的脚本如下 :
PORT=""
CHECK_PORT=0
CONTAINER_ID=""
CONTAINER_NAME=""
IMAGE_NAME=""
DOMAIN="demo.com"
BRANCH=""
#将nginx容器配置文件目录挂载到jenkins_home中
NGINX_CONF_PATH="/var/jenkins_home/nginx/conf.d"
TMP_NGINX_CONF=""
check_port(){
echo "check whether the port is occupied"
result=$(netstat -tlpn|grep "$1")
if [ ! -z "$result" ]; then
echo "again"
CHECK_PORT=0
else
CHECK_PORT=1
fi
}
get_port(){
echo "start random port"
PORT=$(($RANDOM+10000))
#PORT=80
echo "port:${PORT}"
check_port $PORT
if [ $CHECK_PORT = 0 ]; then
get_port
fi
}
cd build
echo $(pwd)
cp ../target/*.jar .
BRANCH=${GIT_BRANCH}
BRANCH=${BRANCH#origin/}
CONTAINER_NAME="demo-$BRANCH"
IMAGE_NAME=demo:$BRANCH
docker rm -f $CONTAINER_NAME 2>/dev/null
docker rmi -f $IMAGE_NAME 2>/dev/null
docker build -t $IMAGE_NAME .
get_port
echo "finally PORT:$PORT"
CONTAINER_ID=$(docker run -it -d -p $PORT:8080 --name $CONTAINER_NAME $IMAGE_NAME)
echo $CONTAINER_ID
##Multi-domain
SERVER="server {
listen 80;
server_name "$BRANCH.$DOMAIN";
location / {
proxy_set_header Host \$host;
proxy_set_header X-Real-Ip \$remote_addr;
proxy_set_header X-Forwarded-For \$remote_addr;
proxy_pass http://172.20.20.25:$PORT;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}"
echo "ouput nginx config"
echo "$SERVER">"$NGINX_CONF_PATH/$CONTAINER_NAME.conf"
echo "restart nginx"
docker exec nginx /usr/sbin/nginx -s reload```