upgradeContainer() {
    PORT=$1
    BUILD_ID=$2
    BACKENDFILE=$3
    CloudImage="registry.cn-hangzhou.aliyuncs.com/wxjk/msy-prod:$BUILD_ID"
    CONTAINER_NAME="msy-$PORT"

    echo "升级容器{$CONTAINER_NAME}"

    # 移除负载均衡
    echo "----移除负载均衡{$PORT}"
    if [ `grep -c "$PORT" $BACKENDFILE` -eq '1' ]; then
        sed -i "/$PORT/"d $BACKENDFILE
    fi

    # 重启nginx
    echo "----重启nginx"
    /usr/local/nginx/sbin/nginx -s reload

    # 删除Docker容器
    if [ `docker ps | grep -c $CONTAINER_NAME` -eq '1' ]; then
        echo "----移除容器{$CONTAINER_NAME}"
        docker rm -f $CONTAINER_NAME
    fi  
    # 清楚未清理的网络桥接
    if [ `docker network inspect bridge|grep -c $CONTAINER_NAME` -eq '1' ]; then
        echo "----移除桥接{$CONTAINER_NAME}"
        docker network disconnect --force bridge $CONTAINER_NAME
    fi

    # 启动Docker容器
    echo "----重启容器{$CONTAINER_NAME}"
    docker run -d -p $PORT:80 --name $CONTAINER_NAME  $CloudImage

    # 加入负载均衡
    echo "----加入负载均衡{$PORT}"
    if [ `grep -c "$PORT" $BACKENDFILE` -eq '0' ]; then
        sed -i "2 a\server 127.0.0.1:$PORT weight=1;" $BACKENDFILE
    fi

    echo "----重启nginx"
    /usr/local/nginx/sbin/nginx -s reload
        
}

# 从云仓库pull要部署的镜像
CloudImage="registry.cn-hangzhou.aliyuncs.com/wxjk/msy-prod:$BUILD_ID"

docker login --username=无邪科技云产品 --password=3344woaini registry.cn-hangzhou.aliyuncs.com 
docker pull $CloudImage
BACKENDFILE="/usr/local/nginx/conf/backend.conf"

upgradeContainer 8090 $BUILD_ID $BACKENDFILE

upgradeContainer 8091 $BUILD_ID $BACKENDFILE

# 删除镜像
docker rmi $CloudImage