创建项目
新建项目
我这里用Spring Web自动生成的demos
启动项目,正常访问,程序没问题
新增Docker构建配置
在项目下新建docker目录,新增Dockerfile、docker-compose.yml
Dockerfile,将mytest.jar 复制到容器的/usr/local/目录下,在/usr/local执行命令java -jar mytest.jar
FROM daocloud.io/library/java:8u40-jdk
COPY mytest.jar /usr/local/
WORKDIR /usr/local
CMD java -jar mytest.jar
docker-compose.yml,当前目录以Dockerfile构建镜像,镜像叫mytest,版本v1.0,容器名字mytest,端口7777
version: '3.1'
services:
mytest:
build:
context: ./
dockerfile: Dockerfile
image: mytest:v1.0
container_name: mytest
ports:
- 7777:8080
修改pom.xml文件
build下添加配置,让jar包以mytest为名(mytest.jar,Docker构建里也是设置的复制名为这个jar包)
<finalName>mytest</finalName>
还有修改主类配置,将主类配置修改如下,默认配置会跳过报错:no main manifest attribute, in mytest.jar
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.monster.mytest.MytestApplication</mainClass>
</manifest>
</archive>
</configuration>
上传代码
将代码上传至Gitlab
Jenkins配置
添加maven、jdk跳过,不行直接让Jenkins自动安装也行
需要现在Jenkins配置-系统管理-系统配置滑动到最下面添加SSH远程服务器(远程的服务器需要安装Docker)
新建个任务,构建一个自由风格的软件项目
源码管理处设置你的git仓库地址,我这里设置的公开的无需账号密码,私有的点击添加按钮添加账号或密钥
Build Steps设置maven,选中你安装的maven名称,目标命令:清理构建跳过测试。
clean package -DskipTests
SSH Publishers,选择我们添加的发布应用的远程服务器。
1.将target目录下所有.jar的文件和docker目录下的所有文件复制到远程应用服务器的/usr/local/test目录下。(Jenkins系统设置里面SSH添加服务器设置的目录路径)
2.这时170.111的/usr/local/test/目录下有target和docker两个目录。我们再添加下面的执行代码,把target目录下人jar包移动到Docker目录里来,然后在执行容器关闭和后台启动构建
cd /usr/local/test/docker
mv ../target/*jar ./
docker compose down
docker compose up -d --build
Jenkins构建
点击Jenkins任务构建按钮
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.906 s
[INFO] Finished at: 2024-03-11T09:03:12Z
[INFO] ------------------------------------------------------------------------
SSH: Connecting from host [3821aea39450]
SSH: Connecting with configuration [应用服务器-170.111] ...
SSH: EXEC: completed after 3,402 ms
SSH: Disconnecting configuration [应用服务器-170.111] ...
SSH: Transferred 3 file(s)
Build step 'Send files or execute commands over SSH' changed build result to SUCCESS
Finished: SUCCESS
构建完成后,会看见170.111服务器自己启来个名称叫mytest容器,映射端口7777,镜像mytest,版本v1.0
访问页面,192.168.170.111:7777
修改项目代码
这里我修改默认的index.html页面内容
只需要把交代码提交到Gitlab
重新Jenkins构建一下
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.760 s
[INFO] Finished at: 2024-03-11T10:43:58Z
[INFO] ------------------------------------------------------------------------
SSH: Connecting from host [3821aea39450]
SSH: Connecting with configuration [应用服务器-170.111] ...
SSH: EXEC: completed after 14,208 ms
SSH: Disconnecting configuration [应用服务器-170.111] ...
SSH: Transferred 3 file(s)
Build step 'Send files or execute commands over SSH' changed build result to SUCCESS
Finished: SUCCESS
刷新页面
评论区