Docker使用jenkins部署java項目到遠程linux(三)


實現功能:從本地提交代碼到gogs上,本地的代碼會被檢測一遍 如果檢測通過才能commit成功 然后可以繼續執行push命令 。push后在gogs上使用web鈎子自動推送到jenkins觸發構建,jenkins構建成功會自動完成項目的部署。

(1)安裝Docker容器(相當於一個linux服務器),在Docker容器里安裝jenkins,gogs.tomcat,jdk

         遠程linux中需要安裝 jdk

 

(2) 使用eclipse創建maven項目,項目目錄結構如下:  (java項目)

  

ApplicationMain.java

package cn.demo.JavademoIn7.application;
/**
 * 測試java項目 in server 172.150.15.7
 * 本地使用git鈎子檢測 findbugs插件
 * gogs上自動推送
 * jenkins也檢測然后自動部署到Docker容器中
 * @author Administrator
 *
 */
public class ApplicationMain {

    public static void main(String[] args) {
        System.out.println("*******************ApplicationMain()****************");
    }
    
    public void hello(){
        System.out.println("This method in demo.");
    }

}

 

ApplicationMainTest.java

package cn.demo.JavademoIn7.application;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
 * ApplicationMain的測試類
 * @author Administrator
 *
 */
public class ApplicationMainTest {
  
  //測試之前執行的方法 @BeforeClass
public static void setUpBeforeClass() throws Exception { System.out.println("---Before()---"); }
  
  //測試執行執行的方法 @AfterClass
public static void tearDownAfterClass() throws Exception { System.out.println("---After()---"); }
  //測試ApplicationMain類中的hello方法 @Test
public void testHello() { System.out.println("executing............."); ApplicationMain amt = new ApplicationMain(); amt.hello(); } }

 

script.sh  (這是執行該項目的腳本命令)

#!/bin/sh
cd  /usr/src/myapp  #進入jar包存放目錄

#得到進程ID pid,kill該進程
pid=`cat  /usr/src/myapp/pid`  #得到該目錄下 pid文件中的進程id
if [ -n "$pid" ]
then
    echo "kill -9 的pid:" $pid
    kill -9 $pid    #kill該進程
fi

#執行jar,並將進程掛起,保存進程ID到 pid文件
echo "Execute shell Finish"
#執行項目jar包,將進程掛起,然后將進程id寫入當前目錄下的pid文件中
BUILD_ID=dontKillMe nohup java -jar /usr/src/myapp/JavademoIn7.jar  & echo "$!" > pid  

 

script.xml (這是將腳本命令打包的描述文件)

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2
          http://maven.apache.org/xsd/assembly-1.1.2.xsd">

    <id>script</id>

    <formats><!--打包的文件格式 -->
        <format>zip</format>
    </formats>

    <fileSets>
        <fileSet>
            <directory>src/main/resources/script</directory><!--需要打包的目錄 -->
            <outputDirectory>/</outputDirectory> <!-- 打包后輸出的路徑 輸出子啊target目錄下 -->
        </fileSet>
    </fileSets>

</assembly>

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

    <groupId>cn.demo</groupId>
    <artifactId>JavademoIn7</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging> <!-- 打包成jar包 -->
    <name>JavademoIn7</name>
    <url>http://maven.apache.org</url>
  
    <build>
        <finalName>JavademoIn7</finalName>
        <plugins>
            <plugin>
                <inherited>true</inherited>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${compiler.source}</source>
                    <target>${compiler.target}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            
            <!-- 指定執行的主類(main方法所在的類)-->
            <plugin>  
                <groupId>org.apache.maven.plugins</groupId>  
                <artifactId>maven-jar-plugin</artifactId>  
                <version>2.6</version>  
                <configuration>  
                    <archive>  
                    <!-- 添加index則不從mainfest中讀取classpath,而是從Index.list中讀取 -->  
                    <!-- <index>true</index> -->  
                        <manifest>  
                            <mainClass>cn.demo.JavademoIn7.application.ApplicationMain</mainClass>  
                        </manifest>  
                       
                    </archive>  
                </configuration>  
            </plugin>  
            
            <!-- 將執行項目的腳本文件一起打包 -->
             <plugin>
               <groupId>org.apache.maven.plugins</groupId> 
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4.1</version>
                <executions>
                    <execution>
                        <id>${project.version}</id><!--名字任意 -->
                        <phase>package</phase>   <!-- 綁定到package生命周期階段上 -->
                        <goals>
                            <goal>single</goal>   <!-- 只運行一次 -->   
                        </goals>
                        
                        <configuration>
                            <descriptors>   <!--描述文件路徑--> 
                                <descriptor>src/main/resources/script.xml</descriptor>
                            </descriptors>
                            <!--這樣配置后,mvn deploy不會把assembly打的zip包上傳到nexus-->
                            <attach>false</attach>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            
        <!-- findbugs插件 :靜態檢查代碼的錯誤-->
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>findbugs-maven-plugin</artifactId>
            <version>3.0.4</version>
            <configuration>
                <!-- 設置分析工作的等級,可以為Min、Default和Max -->
                <effort>Low</effort>
                <!-- Low、Medium和High (Low最嚴格) -->
                <threshold>Medium</threshold>
                <failOnError>true</failOnError>
                <includeTests>true</includeTests>
                <!--findbugs需要忽略的錯誤的配置文件-->
               <!--  <excludeFilterFile>compile.bat</excludeFilterFile> -->
            </configuration> 
            <executions>
                <execution>
                    <id>run-findbugs</id>
                    <!-- 在install 階段觸發執行findbugs檢查,比如執行 mvn clean package-->
                    <phase>install</phase>  
                    <goals>
                        <goal>check</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
            
    </plugins>
    </build>
    
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <compiler.source>1.7</compiler.source>
        <compiler.target>1.7</compiler.target>
        <junit.version>4.12</junit.version>
    </properties>

    <dependencies>
    
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-clean-plugin</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>        
</project>

 

(3)關於git和gogs  代碼存放在gogs管理的倉庫中,本地通過git bash here 界面使用git命令提交代碼

        將Eclipse上的項目復制到桌面,進入項目文件夾,目錄如下:  (紅色標記的是項目中沒有的,需要使用命令生成或手動創建的)

.gitignore 文件的作用:忽略的文件,就是不需要被上傳到gogs的文件  內容如下:

#忽略的文件
.settings
target
.classpath
.project
compile.bat
package.bat
package.sh

 

右擊進入 git bash here 界面,使用 git init 命令,生成 .git文件夾

進入 .git -> hooks   目錄如下(紅色標記的文件是自己添加進去的)

pre-commit文件的作用:在執行 git commit -m "description" 這條命令之前,先執行pre-commit文件中的腳本命令。

這里執行mvn clean install,先清除項目信息,然后再install,前面在pom.xml中配置了 install中嵌套了 findbugs插件的 check命令

所以執行mvn install命令時,也會執行 findbugs:findbugs命令。當檢測出有bug時,會build失敗,commit也失敗;反之則成功

pre-commit內容如下:

#!/bin/sh
#execute shell before commit,check the code
mvn clean install

#recieve the  execute result
result=$?
#output the result ,if the result less or equal 0 ,it proves this project has bugs,otherwise don't.
echo $result

if [ $result -ne 0 ]
then
    mvn findbugs:gui  #返回非0值表示構建失敗,這里彈出findbugs的gui,里面會顯示bug的詳細信息。
    echo "REGRETFUL! BUILD FAILURE"
    exit 1   #這里返回非0值,使得commit失敗。
else
    echo "CONGRATURATION! BUILD SUCCESS"
    exit 0
fi

本地操作命令:

git init    #初始化本地倉庫

git add .  #將所有文件添加到臨時存放區 (被忽略的文件除外)

git commit -m "test java program" #將添加到臨時存放區的文件提交

git remote add origin  http://172.150.12.5:10080/test/JavademoIn7.git  #添加遠程倉庫的連接 這里需要將本機的ssh key 添加到gogs的SSHkey中,如果沒有添加也可以用gogs的登錄賬號和密碼去建立連接

git push origin master #將本地代碼推送到gogs上

 

gogs中的倉庫界面顯示,(推送后)

點擊倉庫設置--》管理web鈎子--》添加web鈎子:  格式如下

http://172.150.15.52:8080/gogs-webhook/?job=JavademoIn7

172.150.15.52:8080 #是訪問jenkins的鏈接

JavademoIn7 #是jenkins的項目名

添加web鈎子的作用: 當下次本地執行 git push命令時,會自動觸發jenkins項目執行構建。

 

(4)jenkins中的配置,jenkins主界面如下

進入 系統管理 --》 Global Tool Configuration  :

JDK勾中自動安裝,maven選擇合適的版本自動安裝,其他的都保持不變,然后保存就行了

 

進入 系統管理 --》插件管理: 界面如下

 

選中 可選擇插件,在紅色標記的這里分別查詢以下插件,並且選擇直接安裝 (安裝jenkins的時候,選擇的是默認安裝方法,其中jenkins會自動下載有些插件)

Maven Intergration plugin, Checkstyle plugin , Findbugs plugin ,Deploy to Container Plugin,Publish over SSH plugin,gogs plugin。

Maven Intergration plugin #用於構建maven項目的插件

Checkstyle plugin #檢測代碼的格式是否規范的插件

Findbugs plugin #對提交的代碼靜態檢測,靜態語法

Deploy to Container Plugin #將項目部署到Tomcat中需要用到的插件 (或者其他容器)

Publish over SSH plugin #需要部署項目到遠程linux時需要到的插件

Gogs plugin #使用web鈎子推送時,必須下載此插件,不然就會報403錯誤

 

插件下載完之后,再進入 系統管理 --》 系統設置 :

前面的配置都不用管,使用默認的就行了。直接下拉到 Publish Over SSH

Passphrase :這里配置的是你在docker容器中,使用  ssh-keygen -t rsa 命令生成秘鑰對時的 passphrse,如果你直接按了回車,這里就不用填寫了

Path to key : 這里寫 Docker容器里  ssh-keygen -t rsa生成 id_rsa 的路徑

key :這里寫  ssh-keygen -t rsa生成的 id_rsa中的內容 

Path to  Key 和 Key二選一就行了,只要填其中一個就可以了。

附: 進入docker容器的命令 docker exec -it 容器ID bash

 

 

接下來配置需要部署項目的遠程linux (SSH Servers),如果需要部署在多台遠程linux上,可以配置多個SSH Servers (下面有增加命令)

Name:這里你自己定義名字,只要非中文,不是非法字符都行

Hostname : 這里可以寫遠程主機名或者是主機IP,建議寫主機IP

Username :用來執行的用戶 一般為root

Remote Directory :這里寫遠程目錄名,/ 表示直接使用根目錄

配置完這里后,記得單擊下面的 高級  按鈕,然后選擇 Use password authentication ,or use a different key

在 Passphrase / password 這里填寫你的  用戶登錄的密碼,就是 root用戶,登錄的密碼

其他的都空着,使用默認的就行,然后下面有個 testConfiguration ,點擊一下,沒問題的話 會出現 SUCCESS

jenkins的基本配置到此結束了,接下來使用jenkins構建項目

 

(5)新建 -- 填寫項目名后 -- 構建maven風格的項目-- ok

  然后開始進行項目的基本配置

  1、General:自己寫項目的基本介紹吧

  

  2、源碼管理 :這里選擇Git 管理

  Repository URL :這里寫你的gogs對應的倉庫鏈接

  Credentials:這里如果沒有配置,點擊右側的Add ,然后填寫 username 和 password  (分別填gogs的登錄名和密碼) 然后再選中就可以了

  

  3、構建觸發器 : 觸發遠程構建

  身份驗證令牌: 填當前jenkins構建的項目名

      

   4、Build :maven項目的構建,命令執行;  Post Step :直接選擇Run only if build success 就行了  (中間的構建環境和 Pre Steps可以不用寫,直接空着)

  Root POM :帶路徑寫出pom.xml的位置,一般是在根目錄下的

  Goals and options :這里寫執行的命令, 先clean ,再 install

  findbugs:findbgus :是執行jenkins中的findbugs插件命令。

  checkstyle:checkstyle:是執行jenkins中的checkstyle插件命令。

   

   5、構建設置 :勾中需要的插件。這里表示使用 checkstyle和findbugs插件

  關於這兩個插件的高級配置,查看以往的博客,里面有詳細介紹。

  

  6、構建后操作:選中 Send build artifacts over SSH

  Name:是你在系統配置--》 SSH server中配置的Name (那邊配置了,這邊下拉框才會有顯示)

  ******Transger :指定是需要被傳輸的內容以及相關命令操作*******

  Source Files : 以項目的工作空間為根目錄,需要傳送到遠程linux的文件直接帶路徑寫上去就行,多個文件使用逗號分隔開

  Remove Prefix:需要被移除的文件前綴

  Remote Directory :這里是被傳送的目錄,遠程linux接收文件的目錄

  Exec command:這里寫腳本命令,由於執行項目的腳本已經通過pom.xml打包好了,在target目錄下的 JavademoIn7-script..zip目錄下,所以這里就寫腳本命令,解壓縮該zip,然后運行里面的腳本文件。

  

Exec command中的內容:

#!/bin/sh
cd /usr/src/myapp/   #進入遠程目錄

unzip -o  /usr/src/myapp/JavademoIn7-script.zip -d  /usr/src/myapp/ #將存放腳本文件的壓縮包解壓

cd JavademoIn7  #打開解壓后的文件夾
sh script.sh #執行腳本文件

 

所有的配置就到這里結束了,保存 --》 執行構建  就行了。

也可以在本地做個小修改,然后重新提交,git add .      git commit -m "re commit to test "    git push origin master  完之后,項目會自動部署到遠程linux。

直接可以在jenkins的 Console Output中查看構建結果。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM