使用Jenkins+shell脚本部署应用至测试环境、生产环境等

结合之前我的博文SpringBoot+GitHub+JenkinsSpringBoot maven多环境打包应用Linux/Mac配置管理ssh会话
可以实现这样的一个持续集成开发场景

  1. 开发者本地进行使用dev配置进行开发,在提交代码到远程仓库之前,将dev改为SpringBoot maven多环境打包应用中提到的[email protected]@
  2. 配置Jenkins,maven打包命令为mvn clean package -DskipTests -P test,配置shell脚本
  3. 配置GitHub或Gitlab远程仓库在有提交的情况下推送push事件至Jenkins
  4. 当代码提交至远程仓库后,远程仓库会向Jenkins推送push事件,Jenkins根据2步骤maven打包命令进行打包,然后Jenkins执行shell脚本将打包好的jar包推送至应用服务器上并运行服务

上面说的这些内容基本在前面的blog中有所体现。下面主要说明4步骤中使用的shell脚本,其主要完成的工作是以ubuntu用户复制jar包至应用服务器,ssh远程登录至应用服务器,关闭docker,执行docker build,重新run服务

su ubuntu <<EOF

# 复制jar包至应用服务器
scp /home/ubuntu/project/prd/$JARNAME [email protected]:/home/ubuntu/hello_server

# ssh远程至应用服务器执行关闭、重启应用的操作
ssh [email protected] << remotessh  
cd /home/ubuntu/hello_server
sudo docker stop hello_server
sudo docker rm hello_server
sudo docker rmi hello/hello_server
sudo docker build -t hello/hello_server .
sudo docker run --name hello_server -d -p 8111:8111 -v /etc/timezone:/etc/timezone -v /etc/localtime:/etc/localtime hello/hello_server
exit
remotessh

EOF

分解上面脚本,下面表示以ubuntu用户执行EOF括起来的内容

su ubuntu <<EOF
{...}
EOF

下面一行脚本是复制jar包至101.154.165.191服务器,使用scp命令本来是需要输入密码的,这里需要按照Linux/Mac配置管理ssh会话配置好,则不需要输入密码

scp /home/ubuntu/project/prd/$JARNAME [email protected]:/home/ubuntu/hello_server

下面使用脚本远程至服务器,使用docker命令关闭、删除、编译、运行docker

ssh [email protected] << remotessh  
cd /home/ubuntu/hello_server
sudo docker stop hello_server
sudo docker rm hello_server
sudo docker rmi hello/hello_server
sudo docker build -t hello/hello_server .
sudo docker run --name hello_server -d -p 8111:8111 -v /etc/timezone:/etc/timezone -v /etc/localtime:/etc/localtime hello/hello_server
exit
remotessh

猜你喜欢

转载自blog.csdn.net/ihtczte/article/details/87094877