tomcat自动化部署(拉取\备份、部署、更新、回滚)

一、传统部署方式及优缺点

1.传统部署方式

(1)纯手工scp

(2)纯手工登录git pull、svn update

(3)纯手工xftp往上拉

(4)开发给打一个压缩包,rz上去;解压

2.缺点

(1)全程运维参与,占用大量时间

(2)上线速度慢

(3)人为失误多,管理混乱

(4)回滚慢,不及时

二、环境规划

1、开发环境--开发者本地有自己的环境。

运维需要设置的开发环境,大家共用的服务。

2、测试环境:功能测试环境和性能测试环境。

3、预生产环境:生产环境集群中的某一个节点。

4、生产环境:直接对用户提供服务的环境。

测试环境与生产环境的数据库不一致时,可能会导致测试的功能不全面,在测试环境测无问题,放在线上可能出现问题

三、需求分析

一、功能需求需求

一个集群有十个节点

1.实现 一键部署10个节点

2.一键回滚到任意版本

3.一键回滚到上个版本

二、部署需求

部署:

1.代码在哪里:svn、git

2.获取什么版本代码?

svn/git:直接拉去某个分支

svn:指定版本号

git:指定tag

3.差异解决:

(1)各个节点直接差异:配置文件未必一致(crontab.xml)。预生产节点。

(2)代码仓库和实际的差异。配置文件是否放在代码仓库中。

4.如何更新

更新时需要考虑是否重启。例如java代码,需要考虑重启tomcat。重启过程中,用户就不能访问了。

5.测试

部署多个节点,某个节点由于配置问题导致部署不成功。如何测试。

6.串行和并行

部署多个节点,串行部署还是并行部署,视具体业务需求决定。

7.如何执行

1.shell脚本,直接执行

2.web界面

三、部署流程

tomcat自动化部署(拉取\备份、部署、更新、回滚)_第1张图片

1.获取代码(直接拉取)----》 2.编译(可选)----》 3.配置文件放进去----》 4.打包 ----》

5.SCP到目标服务器----》 6.将目标服务器移除集群----》 7.解压 ----》 8.放置到webroot ----》

9.SCP差异文件 ----》 10.重启(可选) ----》 11.测试 ----》 12.加入集群

四、代码实现

1、设置无交互访问

通过ssh-keygen将部署机的公钥发送给应用服务器。

注意,这里通常是用普通用户登陆部署机,生成公钥后,再把公钥发给应用服务器

ssh-keygen -t rsa

切换到.ssh目录下

[www@linux-node1 ~/.ssh]$ ll

total 16

-rwx------ 1 www www  397 Jul 31 22:45 authorized_keys

-rwx------ 1 www www 1679 Jul 31 22:44 id_rsa

-rwx------ 1 www www  397 Jul 31 22:44 id_rsa.pub

将id_rsa.pub中的内容复制粘贴到应用服务器的www用户的.ssh目录下,

文件名称为authorized_keys

[www@linux-node2 .ssh]$ cat authorized_keys

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCqT3VwY9Wo7tKsXa4Ce1zXGLT/Iygy30tDBKnV4HW4g5BdUS48urTvYljL9cwJ/HWvoqbtJ5mc7PMmhDMOAjIh1CRZtGxKEkQFB/Xp5cLeAsE7iH+WfkNqavFHD75+YuM2mbNBvisDXO+/pJ/QfbmYwWJ6CW6uLpQKpitdJwrLpQDJGQv5H3aV0kHKZdoA+twdXm0LmQcWWJt7zruPq19CAXG5b93KTdgyt/1x4BfcT5/+PCaEd9suYwEneI2Io8CX9oTAe3MRyRPtlN0szT89qP/q+Q4sktVjc1nkxHhdP2mahqeiBLUGULfkgUBtEjaGAFSWb+ejFV0fRDHk6bSJ www@linux-node1

注意,修改authorized_keys的权限

chmod 600 authorized_keys

另外,将.ssh目录的权限设置成700

chmod 700 .ssh

2、详细代码

 
  
  1. #!/bin/bash
  2. #Node List
  3. PRE_LIST="192.168.56.11"
  4. GROUP1_LIST="192.168.56.12"
  5. ROLLBACK_LIST="192.168.56.11 192.168.56.12"
  6. #Date/Time Variable
  7. LOG_DATE='date "+%Y-%m-%d"'
  8. LOG_TIME='date "+%H-%M-%S"'
  9. CDATE=$(date "+%Y-%m-%d")
  10. CTIME=$(date "+%H-%M-%S")
  11. #Shell env
  12. SHELL_NAME="/deploy1.sh"
  13. SHELL_DIR="/home/www/"
  14. SHELL_LOG="${SHELL_DIR}/${SHELL_NAME}.log"
  15. #Code ENV
  16. PRO_NAME="web-demo"
  17. CODE_DIR="/deploy/code/web-demo"
  18. CONFIG_DIR="/deploy/config/web-demo"
  19. TMP_DIR="/deploy/tmp"
  20. TAR_DIR="/deploy/tar"
  21. LOCK_FILE="/tmp/deploy.lock"
  22. usage(){
  23. echo $"Usage: $0 {deploy | rollback [ list | version ]} "
  24. }
  25. writelog(){
  26. LOGINFO=$
  27. echo "${CDATE}${CTIME}: ${SHELL_NAME}: ${LOGINFO} " >> ${SHELL_LOG}
  28. }
  29. shell_lock(){
  30. touch ${LOCK_FILE}
  31. }
  32. shell_unlock(){
  33. rm -f ${LOCK_FILE}
  34. }
  35. code_get(){
  36. writelog "code_get";
  37. cd $CODE_DIR && echo "git pull";
  38. cp -r ${CODE_DIR} ${TMP_DIR}/
  39. API_VER=""
  40. }
  41. code_build(){
  42. echo code_build
  43. }
  44. code_config(){
  45. writelog "code_config"
  46. /bin/cp -r ${CONFIG_DIR}/base/* ${TMP_DIR}/"${PRO_NAME}"
  47. PKG_NAME="${PRO_NAME}"_"$API_VER"_"${CDATE}-${CTIME}"
  48. cd ${TMP_DIR} && mv ${PRO_NAME} ${PKG_NAME}
  49. }
  50. code_tar(){
  51. writelog "code_tar"
  52. cd ${TMP_DIR} && tar czf ${PKG_NAME}.tar.gz $PKG_NAME
  53. writelog "${PKG_NAME}.tar.gz"
  54. }
  55. code_scp(){
  56. writelog "code_scp"
  57. for node in $PRE_LIST;do
  58. scp ${TMP_DIR}/${PKG_NAME}.tar.gz $node:/opt/webroot
  59. done
  60. for node in $GROUP1_LIST;do
  61. scp ${TMP_DIR}/${PKG_NAME}.tar.gz $node:/opt/webroot
  62. done
  63. }
  64. cluster_node_remove(){
  65. writelog "cluster_node_remove"
  66. }
  67. pre_deploy(){
  68. writelog "remove from cluster"
  69. ssh $PRE_LIST "cd /opt/webroot && tar zxf ${PKG_NAME}.tar.gz"
  70. ssh $PRE_LIST "rm -rf /webroot/web-demo && ln -s /opt/webroot/${PKG_NAME} /webroot/web-demo"
  71. }
  72. url_test(){
  73. URL=$1
  74. curl -s --head $URL|grep "200 OK"
  75. if [ $? -ne 0 ];then
  76. shell_unlock;
  77. writelog "test error" && exit;
  78. fi
  79. }
  80. pre_test(){
  81. url_test "http://${PRE_LIST}/index.html"
  82. echo "add to cluster"
  83. }
  84. group1_deploy(){
  85. writelog "remove from cluster"
  86. for node in $GROUP1_LIST;do
  87. ssh $node "cd /opt/webroot && tar zxf ${PKG_NAME}.tar.gz"
  88. ssh $node "rm -rf /webroot/web-demo && ln -s /opt/webroot/${PKG_NAME} /webroot/web-demo"
  89. done
  90. scp ${CONFIG_DIR}/other/192.168.56.12.crontab.xml 192.168.56.12:/webroot/web-demo/crontab.xml
  91. }
  92. group1_test(){
  93. url_test "http://192.168.56.12/index.html"
  94. echo "add to cluster"
  95. }
  96. rollback_fun(){
  97. for node in $ROLLBACK_LIST;do
  98. ssh $node "rm -rf /webroot/web-demo && ln -s /opt/webroot/$1 /webroot/web-demo"
  99. done
  100. }
  101. rollback(){
  102. if [ -z $1 ];then
  103. shell_unlock;
  104. echo "please input rollback version" && exit;
  105. fi
  106. case $1 in
  107. list)
  108. ls -l /opt/webroot/*.tar.gz
  109. ;;
  110. *)
  111. rollback_fun $1
  112. esac
  113. }
  114. main(){
  115. if [ -f $LOCK_FILE ];then
  116. echo "Deploy is running" && exit;
  117. fi
  118. DEPLOY_METHON=$1
  119. ROLLBACK_VER=$2
  120. case $DEPLOY_METHON in
  121. deploy)
  122. shell_lock;
  123. code_get;
  124. code_build;
  125. code_config;
  126. code_tar;
  127. code_scp;
  128. pre_deploy;
  129. pre_test;
  130. group1_deploy;
  131. group1_test;
  132. shell_unlock;
  133. ;;
  134. rollback)
  135. shell_lock;
  136. rollback $ROLLBACK_VER;
  137. shell_unlock;
  138. ;;
  139. *)
  140. usage;
  141. esac
  142. }
  143. main $1 $2

测试方式

[www@linux-node1 ~]$ curl --head http://192.168.56.11/index.html

HTTP/1.1 200 OK

Date: Mon, 01 Aug 2016 09:42:23 GMT

Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.1e-fips PHP/5.4.16 mod_wsgi/3.4 Python/2.7.5

Last-Modified: Mon, 01 Aug 2016 09:39:52 GMT

ETag: "17-538ff61ca0a00"

Accept-Ranges: bytes

Content-Length: 23

Content-Type: text/html; charset=UTF-8

[www@linux-node1 ~]$ curl -s --head http://192.168.56.11/index.html|grep "200 OK"

HTTP/1.1 200 OK

上面脚本远程执行命令或者拷贝 是使用ssh/scp完成的。当服务器稍多的时候,效率并不高。

我在生产环境中是使用 ansible 替代的,个人感觉对于这个脚本来说,就是个并行、串行的区别。

进一步的发展,还可以开发一些WEB界面去结合这个脚本,做到WEB化自动部署,当然也可以使用开源的jenkis。

3、回滚

1.列出回滚版本

2.目标服务器移除集群

3.执行回滚

4.重启和测试

5.加入集群

===========

如果是遇到重大bug

1.列出回滚版本

2.执行回滚(重启)

==========

非常紧急

1.直接回滚到上个版本(重启)

自动化部署的核心是创建软链接,同样在回滚的时候也能实现秒级回滚。

但是在生产环境中,使用软连接可能会造成WEB打开页面空白,这点需要注意。

python更新tomcat脚本
#!/usr/bin/env python
# _*_ coding:UTF-8 _*_
import commands
import time,os,sys
from download_bag import downloadbag

tomcat_home = '/usr/local/apache-tomcat-7.0.42/'
webapp_name = 'front'
update_dir = "/home/deployer/update/"
backup_home = '/home/deployer/backup_war'
uptime = time.strftime('%Y%m%d',time.localtime(time.time()))
backup_time = time.strftime('%Y%m%d_%H%M',time.localtime(time.time()))

#关闭tomcat
def shutdown():
    print "准备关闭tomcat......"
    status,output=commands.getstatusoutput('ps -ef|grep -i '+tomcat_home+'|wc -l')
    if(int(output)>2): #判断是否有tomcat进程
        print "    开始关闭tomcat"
        status,output=commands.getstatusoutput(tomcat_home+'bin/shutdown.sh')
        if(status!=0):
            print output
            sys.exit(1)
        time.sleep(0.5) #关闭程序缓存时间
        status,output=commands.getstatusoutput('ps -ef|grep -i '+tomcat_home+'|wc -l')
        if(int(output)>2): #判断是否关闭成功
            print "    强制关闭tomcat"
            status,output=commands.getstatusoutput('kill -9 `ps -ef|grep -i '+tomcat_home+' |awk \'NR==1{print $2}\'`')
            if(status!=0):
                print output
                sys.exit(1)
        print "    已关闭tomcat"
        return 0
    print "    tomcat未启动"

#备份tomcat
def backup():
    print "开始备份......"
    #判断今日备份目录是否存在,不存在则创建
    if(not os.path.exists(backup_home+'/'+webapp_name+'/'+backup_time)):
        status,output=commands.getstatusoutput('mkdir -p '+backup_home+'/'+webapp_name+'/'+backup_time)
        if(status!=0):
            print output
            sys.exit(1)
#    #备份当前版本,备份前先判断目录是否是空的
    if(len(os.listdir(tomcat_home+'webapps/'))>0):
        status,output=commands.getstatusoutput('mv '+tomcat_home+'webapps/* '+backup_home+'/'+webapp_name+'/'+backup_time)
        if(status!=0):
            print output
            sys.exit(1)
    print '    备份成功'


from download_bag import downloadbag
#部署新程序
def update():
    print "开始部署....."
    #部署新war包到tomcat里
    status,output=commands.getstatusoutput('cp -rf '+update_dir+uptime+'/'+webapp_name + '.war ' + tomcat_home+'webapps/')
    if(status!=0):
        print output
        sys.exit(1)
    #启动tomcat
    status,output=commands.getstatusoutput(tomcat_home+'bin/startup.sh')
    print output

if __name__ == '__main__':
       if os.geteuid() == 0:
            print '''
                  ***************************************************************************
                  **********  hi,hi,hi.......请注意                             ***************
                  *********  不能用root账号,请使用deployer账号,现在正在退出' ***************
                  *********  exit now                                                 ********
                  '''
            sys.exit(1)
       else:
            downloadbag()
            shutdown()
            backup()
            update()

 
python之tomcat自动化备份,更新
由于tomcat开始集群,部署较为不变,于是写了个python自动化更新备份脚本

复制代码
#!/usr/local/bin/python3
#coding:utf-8

import os, sys, subprocess, time, shutil

site_file = 'xxxxxi'
update_file = '/home/sourcedir/' + site_file + '.war'
webapps_file = '/var/tomcat2/webapps/' + site_file + '.war'
webapps_dir = '/var/tomcat2/webapps/' + site_file
bakwebapps_file = '/var/tomcat2/bakwebapps/' + site_file + '.war'
bakwebapps_dir = '/var/tomcat2/bakwebapps/' + site_file

tomcat_pid =  ((subprocess.Popen("lsof -i :8081 |grep root |awk '{print $2}'", shell=True, stdout=subprocess.PIPE)).stdout.read()).decode()

print("Tomcat will shutdown after 6s, u can enter Ctrl + c interrupt it ! ")
for i in range(3):
    print("." ,end = "")
    sys.stdout.flush()
    time.sleep(1)

print()
if len(tomcat_pid) == 0:
    print("> tomcat already shutdown!")
else:
    subprocess.Popen("/usr/local/tomcat/bin/shutdown.sh > /dev/null 2>&1", shell=True, stdout=subprocess.PIPE)

for i in range(3):
    print("." ,end = "")
    sys.stdout.flush()
    time.sleep(1)
    
if len(tomcat_pid) == 0: 
    pass 
else :
   subprocess.Popen("kill -9 " + tomcat_pid, shell=True, stdout=subprocess.PIPE)
   print("\n> Tomcat close the failure, kill the pid %s" % tomcat_pid) 
   
#备份旧站点
print("\n--------Begin to backup webapps---------\n")
 
if os.path.exists(bakwebapps_file):
    shutil.rmtree(bakwebapps_dir)
    print("> Old bak webapps has been deleted!")
    os.remove(bakwebapps_file)
else:
    pass


shutil.copyfile(webapps_file, bakwebapps_file)    
shutil.copytree(webapps_dir, bakwebapps_dir)
for i in range(3):
    print("." ,end = "")
    sys.stdout.flush()
    time.sleep(1)
print("\n> Backup completed,Start to update the program...")
shutil.copyfile(update_file, webapps_file)

print("\n> Update completed,start tomcat")
subprocess.Popen("/usr/local/tomcat/bin/startup.sh", shell=True, stdout=subprocess.PIPE)

for i in range(3):
    print("." ,end = "")
    sys.stdout.flush()
    time.sleep(1)
tomcat_pid2 =  ((subprocess.Popen("lsof -i :8081 |grep root |awk '{print $2}'", shell=True, stdout=subprocess.PIPE)).stdout.read()).decode()

if len(tomcat_pid2) == 0:
    print("\n> Tomcat has not start, Please check u program!")
else:
    print("\n> Tomcat have already started !")

tomcat自动备份部署及回滚脚本

1、备份

#!/bin/bash
datestr=`date +'%Y%m%d%H%M%S'`
echo 'back up start...'
mkdir -p /home/billserver/bakups/$datestr/
echo "back up to /home/billserver/bakups/$datestr/"
echo "cp /alidata1/tomcat8/open/* /home/billserver/bakups/$datestr/ -r"
cp /alidata1/tomcat8/open/* /home/billserver/bakups/$datestr/ -r
echo "cp /alidata1/tomcat8/unified/* /home/billserver/bakups/$datestr/ -r"
cp /alidata1/tomcat8/unified/* /home/billserver/bakups/$datestr/ -r
echo 'back up finish...'
2、发布(会引用备份脚本完成备份)

#!/bin/bash
echo 'you will full deploy[open,unified],input yes to continue'
read tc
if [ $tc = 'yes' ]; then
        echo 'full deploy start...'
        #backup
        /home/billserver/sh/bakupapi
        #stutdown tomcat
        echo "stutdown tomcat"
        ps -ef | grep tomcat | grep java | awk '{print $2}' | xargs kill -9
        #clean old
        echo "clean old"
        echo "rm /alidata1/tomcat8/open/* -rf"
        rm /alidata1/tomcat8/open/* -rf
        echo "rm /alidata1/tomcat8/unified/* -rf"
        rm /alidata1/tomcat8/unified/* -rf
        echo "cp wars"
        cp /home/billserver/tmp/unified-0.1.war /alidata1/tomcat8/unified/ROOT.war
        cp /home/billserver/tmp/open-0.1.war /alidata1/tomcat8/open/ROOT.war
        sleep 2
        #startup tomcat
        /alidata1/tomcat8/bin/startup.sh
        echo 'full deploy finish...'
else
        echo 'cancel...'
fi
3、回滚

#!/bin/bash
if [ $1 == '' ];then
    echo "please specify backup fold name";
    exit 0
fi
echo 'you will full rollback[open,unified],bakup fold='$1',input yes to continue'
read tc
if [ $tc = 'yes' ]; then 
    echo 'full rollback start...'
    #backup
    /home/ireader/sh/bakupapi
    #stutdown tomcat
    echo "stutdown tomcat"
    ps -ef | grep tomcat | grep java | awk '{print $2}' | xargs kill -9
    #clean old
    echo "clean old"
    echo "rm /alidata1/tomcat8/open/* -rf"
    rm /alidata1/tomcat8/open/* -rf
    echo "rm /alidata1/tomcat8/unified/* -rf"
    rm /alidata1/tomcat8/webapps/unified/* -rf
    echo "cp wars"
    cp /home/ireader/bakups/$1/open.war /alidata1/tomcat8/open/ROOT.war -r
    cp /home/ireader/bakups/$1/unified.war /alidata1/tomcat8/unified/ROOT.war -r
    sleep 2
    #startup tomcat
    /alidata1/tomcat8/bin/startup.sh
    echo 'full rollback finish...'
else
    echo 'cancel...'
fi

tomcat自动部署脚本
#!/bin/bash

#defined

now=`date +%Y%m%d%H%M%S`

TOMCAT_HOME="/usr/tomcat7/apache-tomcat-7.0.70/"

TOMCAT_PORT=8080

PROJECT="$1"

BACKUP_DIR="/tomcat_back/$PROJECT/$now"

#param validate;

if [ $# -lt 1 ]; then

  echo "you must use like this : ./publish.sh [tomcat port] [tomcat home dir]"    

  exit

fi

if [ "$2" != "" ]; then

   TOMCAT_PORT=$2

fi

if [ "$3" != "" ]; then

   TOMCAT_HOME="$3"

fi

#shutdown tomcat

"$TOMCAT_HOME"/bin/shutdown.sh

echo "tomcat shutdown"

#check tomcat process

# tomcat_pid=`/usr/sbin/lsof -n -P -t -i :$TOMCAT_PORT`

tomcat_pid=`ps aux|grep "java"|grep "$TOMCAT_HOME"|awk '{printf $2}'`

while [ -n "$tomcat_pid" ]

do

 echo "current :" $tomcat_pid

 kill -9 $tomcat_pid

 echo "scan tomcat pid :" $tomcat_pid

done

#publish project

echo "scan no tomcat pid,$PROJECT publishing"

rm -rf "$TOMCAT_HOME"/webapps/$PROJECT*

cp /save/$PROJECT*.war "$TOMCAT_HOME"/webapps/$PROJECT.war

#bak project and may be create backup dir

if [ ! -d "$BACKUP_DIR" ]; then

 mkdir -p "$BACKUP_DIR"

fi

cp "$TOMCAT_HOME"/webapps/$PROJECT.war "$BACKUP_DIR"/"$PROJECT"_`date +%H%M%S`.war

#remove tmp

rm -rf /save/$PROJECT*.war

#start tomcat

"$TOMCAT_HOME"/bin/startup.sh

tail -10f "$TOMCAT_HOME/logs/catalina.out"

echo "#############################################################"

echo "tomcat is starting,please try to access $PROJECT conslone url"

echo "#############################################################"

每一步的注释还算清楚,因为公司项目本身没有采用专业的源码管理工具来管理项目,所以此脚本还要准备好相应的不同平台的配置文件,需要更改默认的项目配置文件,如果有专业的源码管理,那就不用这么啰嗦了,直接使用该脚本就可以部署tomcat的工程了

######################## 以下为更新后的脚本 ##########################

#!/bin/bash

#defined

TOMCAT_HOME="/usr/tomcat7/apache-tomcat-7.0.70"

TOMCAT_PORT=8080

PROJECT="$1"

#param validate

if [ $# -lt 1 ]; then

  echo "you must use like this : ./publish.sh [tomcat port] [tomcat home dir]"

  exit

fi

if [ "$2" != "" ]; then

   TOMCAT_PORT=$2

fi

if [ "$3" != "" ]; then

   TOMCAT_HOME="$3"

fi

#shutdown tomcat

"$TOMCAT_HOME"/bin/shutdown.sh

echo "tomcat shutdown"

#check tomcat process

tomcat_pid=`/usr/sbin/lsof -n -P -t -i :$TOMCAT_PORT`

echo "current :" $tomcat_pid

while [ -n "$tomcat_pid" ]

do

 tomcat_pid=`/usr/sbin/lsof -n -P -t -i :$TOMCAT_PORT`

 kill -9 $tomcat_pid

 echo "scan tomcat pid :" $tomcat_pid

done

#publish project

echo "scan no tomcat pid,$PROJECT publishing"

rm -rf "$TOMCAT_HOME"/webapps/$PROJECT*

cp /save/$PROJECT*.war "$TOMCAT_HOME"/webapps/$PROJECT.war

#bak project

BAK_DIR=/save/bak/$PROJECT/`date +%Y%m%d`

mkdir -p "$BAK_DIR"

cp "$TOMCAT_HOME"/webapps/$PROJECT.war "$BAK_DIR"/"$PROJECT"_`date +%H%M%S`.war

#remove tmp

rm -rf /save/$PROJECT*.war

#start tomcat

"$TOMCAT_HOME"/bin/startup.sh

sleep 5

#echo "tomcat is starting,please try to access $PROJECT conslone url"

### change the configure file ###由于在shell脚本中处于非交互模式,所以alias功能是未开启的,然后强制复制项目的配置文件到tomcat应用里面

shopt -s expand_aliases

unalias cp

cp -af /save/configfile/*   /usr/tomcat7/apache-tomcat-7.0.70/webapps/manage/WEB-INF/classes/

### restart tomcat application

"$TOMCAT_HOME"/bin/shutdown.sh

### check tomcat process agion

tomcat_pid=`ps aux|grep "java"|grep "$TOMCAT_HOME"|awk '{print $2}'`

if [ -n "$tomcat_pid" ];then

    echo "current :" $tomcat_pid

    kill -9 $tomcat_pid

else

    echo "no tomcat process"

fi

### start tomcat

"$TOMCAT_HOME"/bin/startup.sh

echo "###################################################"

echo "# tomcat is starting.pleage check the logs for it #"

echo "###################################################"

到此,此脚本告一段落,注意此脚本备份的是上传的项目,而非上次的项目,如果自己有需求,要注意配置相关部分
 
 
 Tomcat 自动部署、回滚(java project)脚本
 Tomcat 自动部署
自动部署java项目,从打包服务器scp项目war到本地,本地启动tomcat

#!/bin/bash
#############################################################################
# Functions: auto deploy api project, base on tomcat
#############################################################################
# ChangeLog:
# 2016-12-19    wanghui    initial create
#
#############################################################################
# set some variables
Date=`date +%F_%T`
DATE=`date +Y-%m-%d`
Project=project_name
Back_dir=/data/war_back/$Project
Wget_dir=/data/wget

Old_project=/data/svn
#New_project=/data/svn/aniu-project

# make sure define folder was created
[ -d $Back_dir ] || mkdir -p $Back_dir
[ -d $Wget_dir ] || mkdir -p $Wget_dir

# backup in use project war to back_dir
/bin/mv $Wget_dir/$Project.war $Back_dir/$Project_$Date.war

# upload project war from remote server 
/usr/bin/scp -P54077 root@remote_ip:$Old_project/aniu-api/target/$Project.war $Wget_dir/

for port in 8082 8083 8084
  do
  Tomcat_port=tomcat_$port
  Project_home=/data/$Tomcat_port
  Project_dir=$Project_home/webapps
#  echo "*** First step shutdown $Tomcat_port ***"
  /bin/bash $Project_home/bin/shutdown.sh
  tomcat_status=`ps -ef | grep $Tomcat_port | grep -v grep | awk '{print $2}' | wc -l`
  if [ $tomcat_status -eq 0 ];then
       echo "*** $Tomcat_port auto shutdown succeed!  ***"
    else
#       echo "*******************************************************************************"
#       echo "*** $Tomcat_port auto shutdown failed,then should force shutdown $Tomcat_port! " 
       ps -ef | grep $Tomcat_port | grep -v grep | awk '{print $2}' | xargs kill -9
       tomcat_pid=`ps -ef | grep $Tomcat_port | grep -v grep | awk '{print $2}'`
       /bin/kill -9 tomcat_pid
  fi
  /bin/rm -rf $Project_dir/$Project*
  /bin/cp $Wget_dir/$Project.war $Project_dir/
  /bin/bash $Project_home/bin/startup.sh
#  echo "-----------------------------------------------------------------------------------"
  tomcat_pid=`ps -ef | grep $Tomcat_port | grep -v grep | awk '{print $2}'`
  if [ $tomcat_pid -ne 0 ];then
     echo "*************************************************"
     echo "***      $Tomcat_port auto start succeed !    ***"
     echo "*************************************************"
  else
     echo "### $Tomcat_port auto start failed! #####"
     echo "#########################################"
  fi
done
 
Tomcat 回滚
回滚最近三次的部署

#!/bin/bash
##########################################################################
# Script Name: rollback_api.sh
# Author: shaon
# Email: [email protected]
# Created Time: Tue 20 Dec 2016 07:56:59 PM CST
#########################################################################
# Blog address: http://blog.csdn.net/wh211212
#########################################################################
# Define some variables #
Date=`date +%F_%T`
DATE=`date +Y-%m-%d`
Project=aniuapi
Back_dir=/data/war_back/$Project
Wget_dir=/data/wget

# Move to Back_dir watch which time deploy you want Rollback
echo "-----------------------------------------------------"
echo "  Three last deploy version "
ls -ltr $Back_dir | tail -3 > /tmp/version.txt
cat /tmp/version.txt
read -p "which version war you want rollback: " version

# Begin rollback all api
echo "-----------------------------------------------------"
echo "----       Begin rollback all api!               ----"
echo "-----------------------------------------------------"
# Copy need rollback api.war to wget_dir
  /bin/cp -f $Back_dir/$version $Wget_dir/$Project.war

  for port in 8082 8083 8084
    do
    Tomcat_port=tomcat_$port
    Project_home=/data/$Tomcat_port
    Project_dir=$Project_home/webapps
  #  echo "*** First step shutdown $Tomcat_port ***"
    /bin/bash $Project_home/bin/shutdown.sh
    tomcat_status=`ps -ef | grep $Tomcat_port | grep -v grep | awk '{print $2}' | wc -l`
    if [ $tomcat_status -eq 0 ];then
         echo "*** $Tomcat_port auto shutdown succeed!  ***"
      else
  #       echo "*******************************************************************************"
  #       echo "*** $Tomcat_port auto shutdown failed,then should force shutdown $Tomcat_port! " 
         ps -ef | grep $Tomcat_port | grep -v grep | awk '{print $2}' | xargs kill -9
         tomcat_pid=`ps -ef | grep $Tomcat_port | grep -v grep | awk '{print $2}'`
         /bin/kill -9 tomcat_pid
    fi
    /bin/rm -rf $Project_dir/$Project*
    /bin/cp $Wget_dir/$Project.war $Project_dir/
    /bin/bash $Project_home/bin/startup.sh
  #  echo "-----------------------------------------------------------------------------------"
    tomcat_pid=`ps -ef | grep $Tomcat_port | grep -v grep | awk '{print $2}'`
    if [ $tomcat_pid -ne 0 ];then
       echo "*****************************************************"
       echo "***      $Tomcat_port auto rollback succeed !     ***"
       echo "******************************************************"
    else
       echo "### $Tomcat_port auto rollabck failed! #####"
       echo "#############################################"
    fi
  done 
#
rm -f /tmp/version.txt
 
shell脚本自动部署tomcat项目
自动部署shell脚本由4个方法组成: deploy_backup(版本备份)、deploy_unzip(自动解压新版本)、deploy_restart(重启tomcat)、deploy_Rollback(版本回滚),当然,每个方法可以独立执行,此处在开始运行脚本时给出了2个选择,0:版本回滚,其他任意输入会自动部署新的版本包并重启tomcat。shell脚本代码如下:

#!/bin/bash  
deploy installation script By clinva 2015.08.28  


#版本部署路径  
mainpath=/home/emalls1/qdone/pcv2  

#备份版本包  
deploy_backup()  
{  
cd ${mainpath}/tomcat8/webapps/;  
tar -zcvf epc_`date +%y%m%d%H%M%S`.tar.gz epc;  
sleep 3  
ls;  
mv *.tar.gz ${mainpath}/backup/;  
}  


#解压版本包  
deploy_unzip()  
{  
cd ${mainpath};  
ls;  
sleep 3;  
#unzip -l *.zip;  
unzip -o -d ./tomcat8/webapps/epc pc.zip;  
sleep 3;  
}  

#重启tomcat  
deploy_restart()  
{  
cd ${mainpath}/tomcat8/bin;  
pid1=`ps -ef|grep emalls1 |grep pcv2 |grep tomcat8 |grep qdone |awk '{print $2}'`  
echo $pid1  
if [ -z $pid1 ]; then  
        echo "not exist"  
        ./startup.sh;  
    tailf ./../logs/catalina.out  
        exit 1  
else  
        echo "restarting tomcat1"  
        kill -9 $pid1  
        sleep 5  
        ./startup.sh;  
        tailf ./../logs/catalina.out  
fi  
}  


#版本回滚  
deploy_Rollback()  
{  
#进入备份文件夹  
    cd ${mainpath}/backup/  
    #获取最新备份文件  
    file_name_new=''  
    for i in `ls -tr`;  
    do  
        echo $i;  
        file_name_new=$i;  
    done;  
    #将备份文件复制到webapps  
    cp  ${mainpath}/backup/${file_name_new} ${mainpath}/tomcat8/webapps  
    if [ $? -eq 0 ]  
    then  
        echo 复制${file_name_new}成功  
    else  
        echo 复制失败,退出!  
    exit 1  
    fi  
    #进入webapps/目录  
    cd  ${mainpath}/tomcat8/webapps  
    #解压文件  
    echo 正在解压,请稍后...  
    tar -zxvf ${file_name_new}  
    #重启tomcat  
    deploy_restart  
}  


echo --------欢迎使用shell自动部署脚本--------  
echo -e "请输入对应的操作编号:\n0.版本包回滚;\n其他键.一件部署;"  
#获取用户操作  
read wm2  
case $wm2 in  
0)  
    deploy_Rollback  
    ;;  
*)  
    deploy_backup  
    deploy_unzip  
    deploy_restart  
    ;;  
esac  

简单linux自动部署tomcat脚本
 
#!/bin/sh
echo ‘####################tomcat1开始自动部署####################’
path=pwd #当前路径
tomcatPath=/home/tomcat/apache-tomcat-8.5.8 #指定tomcat文件目录名称
appname=ROOT.war
cd $tomcatPath/bin #进入tomcat的bin目录

获取tomcat进程ID
TomcatID=$(ps -ef | grep ${tomcatPath} | grep -v ‘grep’ | awk ‘{print $2}’)
if [ T o m c a t I D ] ; t h e n e c h o " [ i n f o ] 当 前 t o m c a t 进 程 I D 为 : TomcatID ];then echo "[info]当前tomcat进程ID为: TomcatID];thenecho"[info]当前tomcat进程ID为:TomcatID"
kill -9 $TomcatID
fi
sleep 1 #休眠1s
cd …/webapps #进入tomcat的webapps目录
rm -fr ROOT #删除test文件目录
mv $appname a p p n a m e . appname. appname.(date +%Y%m%d) #备份webapps下的test
cp /root/java/$appname ./ #复制test.war到webapps路径下
sleep 1 #休眠1s
cd …/bin
./startup.sh #启动tomcat服务
echo ‘####################tomcat1部署结束####################’

echo ‘############5s后将部署tomcat2##########’

sleep 5 #避免同时启动时用户访问程序出错,5s后进行tomcat2的部署

echo ‘####################tomcat2开始自动部署####################’
path=pwd #当前路径
tomcat2Path=/home/tomcat/tomcat2 #指定tomcat文件目录名称
appname=ROOT.war
cd $tomcat2Path/bin #进入tomcat的bin目录

获取tomcat进程ID
Tomcat2ID=$(ps -ef | grep ${tomcat2Path} | grep -v ‘grep’ | awk ‘{print $2}’)
if [ T o m c a t 2 I D ] ; t h e n e c h o " [ i n f o ] 当 前 t o m c a t 进 程 I D 为 : Tomcat2ID ];then echo "[info]当前tomcat进程ID为: Tomcat2ID];thenecho"[info]当前tomcat进程ID为:Tomcat2ID"
kill -9 $Tomcat2ID
fi
sleep 1 #休眠1s
cd …/webapps #进入tomcat的webapps目录
rm -fr ROOT #删除test文件目录
mv $appname a p p n a m e . appname. appname.(date +%Y%m%d) #备份webapps下的test
cp /root/java/$appname ./ #复制test.war到webapps路径下
sleep 1 #休眠1s
cd …/bin
./startup.sh #启动tomcat服务
echo ‘####################tomcat2部署结束####################’

 

你可能感兴趣的:(tomcat,自动化,运维)