序言
在SpringBoot項目部署的時候,我了解到了Jib插件的強大,這個插件可以快速構建鏡像發布到我們的鏡像倉庫當中去。於是我打算在畢設當中加上這個功能,並且整合到github actions中去。
阻礙
在單體地獄的項目中,我們使用jib插件十分的方便,只需要在項目文件夾下運行命令:mvn complie jib:build
就可以完成鏡像的構建並且推送到倉庫。詳情見:jib-maven-plugin構建鏡像
可是這種方法在SpringCloud這種多模塊化項目當中肯定是無法實現的。假設當前maven工程是父子結構的,有兩個子工程A和B,其中A是二方庫,提供一個jar包,里面是接口類和Bean類,B是springboot應用,並且B的源碼中用到了A提供的接口和Bean;上述父子結構的maven工程是常見的工程結構,此時如果要將B構建成Docker鏡像,在B的目錄下執行mvn compile jib:build
顯然是不行的,因為沒有編譯構建A,會導致B的編譯失敗;
解決辦法
此時最好的做法就是將jib
與mvn
構建的生命周期綁定,修改B的pom.xml
文件,加入executions
節點;
父工程目錄下執行mvn package
,此時maven
會先編譯構建整個工程,然后再將B工程的構建結果制作成鏡像;
實例
一、目錄結構
這是我的SpringCloud
項目的目錄結構,我們需要修改的內容為需要發布到倉庫的服務的pom
文件,例如:
二、通過<executions>
節點綁定生命周期
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>1.8.0</version>
<!-- executions start-->
<executions>
<execution>
<id>build-image</id>
<phase>package</phase>
<goals>
<goal>build</goal>
</goals>
</execution>
</executions>
<!-- executions end-->
<configuration>
<from>
<image>registry.cn-hangzhou.aliyuncs.com/yhhu/jdk8</image>
</from>
<to>
<image>registry.cn-hangzhou.aliyuncs.com/2shop/user_provider</image>
</to>
<container>
<useCurrentTimestamp>true</useCurrentTimestamp>
<args>
<arg>--spring.profiles.active=prod</arg>
</args>
</container>
<allowInsecureRegistries>true</allowInsecureRegistries>
</configuration>
</plugin>
三、與github actions
整合,實現push
后自動構建鏡像
github action文件如下:
name: Cloud CI
on:
push:
branches:
- master
pull_request:
jobs:
push_docker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
server-id: registry.cn-hangzhou.aliyuncs.com
server-username: MAVEN_USERNAME
server-password: MAVEN_PASSWORD
- name: Build
run: mvn package -q -B -V
env:
MAVEN_USERNAME: ${{secrets.DOCKER_USERNAME}}
MAVEN_PASSWORD: ${{secrets.DOCKER_PASSWORD}}