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

  • Post author:
  • Post category:其他


结合之前我的博文

SpringBoot+GitHub+Jenkins



SpringBoot maven多环境打包应用



Linux/Mac配置管理ssh会话


可以实现这样的一个持续集成开发场景

  1. 开发者本地进行使用dev配置进行开发,在提交代码到远程仓库之前,将dev改为

    SpringBoot maven多环境打包应用

    中提到的

    spring.profiles.active=@spring.profiles.active@
  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 ubuntu@101.154.165.191:/home/ubuntu/hello_server

# ssh远程至应用服务器执行关闭、重启应用的操作
ssh ubuntu@101.154.165.191 << 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 ubuntu@101.154.165.191:/home/ubuntu/hello_server

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

ssh ubuntu@101.154.165.191 << 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



版权声明:本文为ihtczte原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。