GitLab + Jenkins实现CI/CD

GitLab安装使用

官网:https://about.gitlab.com/

在SSH下安装

官方安装文档:https://gitlab.cn/install/?version=ce

安装依赖

sudo yum install -y curl policycoreutils-python openssh-server perl
sudo systemctl enable sshd
sudo systemctl start sshd

配置镜像

curl -fsSL https://packages.gitlab.cn/repository/raw/scripts/setup.sh | /bin/bash

开始安装

sudo EXTERNAL_URL="http://改成自己的IP地址" yum install -y gitlab-jh

GitLab常用命令

gitlab-ctl start                  # 启动所有 gitlab 组件;
gitlab-ctl stop                   # 停止所有 gitlab 组件;
gitlab-ctl restart                # 重启所有 gitlab 组件;
gitlab-ctl status                 # 查看服务状态;
gitlab-ctl reconfigure            # 启动服务;
vi /etc/gitlab/gitlab.rb         # 修改默认的配置文件;
gitlab-ctl tail                   # 查看日志;

登录

访问:自己的IP地址

当首次运行出现502错误的时候排查两个原因

  1. 虚拟机内存至少需要4g
  2. 稍微再等等刷新一下可能就好了

用户名:root

密码存在下面文件中,登录后需要改密码不然24小时之后会失效

cat /etc/gitlab/initial_root_password

Jenkins安装使用

安装JDK

最新版Jenkins建议安装JDK21

mkdir /usr/local/java
  • 将压缩包解压到存放目录
tar -zxvf jdk-21_linux-x64_bin.tar.gz -C /usr/local/java
  • 切换至JDK存储目录
cd /usr/local/java
  • 配置JAVA环境变量:一般linux可能会有自己自带的java环境,它已经占用了/usr/bin/java 的这个软链接,所以要先删除
rm -rf /usr/bin/java
  • 然后重新创建 java 软链接到 /usr/bin/ 目录下
ln -s /usr/local/java/jdk-21.0.5/ /usr/bin/java、
  • 编辑系统配置文件
vi /etc/profile
  • 然后输入以下内容
export JAVA_HOME=/usr/bin/java
export PATH=$JAVA_HOME/bin:$PATH
  • 激活配置文件
source /etc/profile
  • 验证java安装是否成功
java --version

安装Maven

官网:https://maven.apache.org/

下载后复制到Jenkins所在服务器解压缩即可

安装Jenkins

下载Jenkins的war包https://www.jenkins.io/download/

  • 将包存放至root目录下
  • 运行:默认是8080端口
java -jar jenkins.war

image-20250606193611660.png

  • 继续后,选择安装推荐的插件
    image-20250606193644589.png
  • 成功后,会进入Jenkins控制台
    image-20250606193721007.png
  • 安装插件:maven和publish over ssh
    image-20250606193811782.png

image-20250606193844091.png

image-20250606193912563.png

Jenkins + Git + Maven 自动化部署配置

新建项目

image-20250606194010294.png

Git配置

image-20250606194041059.png

  • Repository URL:填写GitLab的项目地址
  • Branches to build:指定分支填写实际的主分支

Maven配置

image-20250606194420039.png
image-20250606194435741.png

pom.xml配置

image-20250606194500337.png

Git安装

yum install -y git

Maven阿里云镜像

  • 修改/usr/local/maven/conf/settings.xml
<?xml version="1.0" encoding="UTF-8"?>
​
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at
​
    http://www.apache.org/licenses/LICENSE-2.0
​
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
​
<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.conf}/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
  <localRepository>${user.home}/.m2/repository</localRepository>
  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->
​
  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->
​
  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
    <pluginGroup>org.mortbay.jetty</pluginGroup>
  </pluginGroups>
​
  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>
​
  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     | 
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are 
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->
    
    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
    <server>
        <id>releases</id>
        <username>ali</username>
        <password>ali</password>
      </server>
      <server>
        <id>Snapshots</id>
        <username>ali</username>
        <password>ali</password>
      </server>
  </servers>
​
  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
    <mirror>
      <!--This sends everything else to /public -->
      <id>nexus</id>
      <mirrorOf>*</mirrorOf> 
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
    </mirror>
    <mirror>
      <!--This is used to direct the public snapshots repo in the 
          profile below over to a different nexus group -->
      <id>nexus-public-snapshots</id>
      <mirrorOf>public-snapshots</mirrorOf> 
      <url>http://maven.aliyun.com/nexus/content/repositories/snapshots/</url>
    </mirror>
    <mirror>
      <!--This is used to direct the public snapshots repo in the 
          profile below over to a different nexus group -->
      <id>nexus-public-snapshots1</id>
      <mirrorOf>public-snapshots1</mirrorOf> 
      <url>https://artifacts.alfresco.com/nexus/content/repositories/public/</url>
    </mirror>
  </mirrors>
​
  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
   <profiles> 
    <profile>
      <id>development</id>
      <repositories>
        <repository>
          <id>central</id>
          <url>http://central</url>
          <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
          <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
        </repository>
      </repositories>
     <pluginRepositories>
        <pluginRepository>
          <id>central</id>
          <url>http://central</url>
          <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
          <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
    <profile>
      <!--this profile will allow snapshots to be searched when activated-->
      <id>public-snapshots</id>
      <repositories>
        <repository>
          <id>public-snapshots</id>
          <url>http://public-snapshots</url>
          <releases><enabled>false</enabled></releases>
          <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
        </repository>
      </repositories>
     <pluginRepositories>
        <pluginRepository>
          <id>public-snapshots</id>
          <url>http://public-snapshots</url>
          <releases><enabled>false</enabled></releases>
          <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
 
   <activeProfiles>
    <activeProfile>development</activeProfile>
    <activeProfile>public-snapshots</activeProfile>
   </activeProfiles>
​
  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>
​

publish over ssh 配置

image-20250606194709092.png

image-20250606194657498.png

  • Hostname:填写测试服务目标地址
  • 高级选项中配置密码

在Item中配置Post Steps
image-20250606194851511.png

超时机制

输出命令时一定要注意不要让窗口卡主,不然Jenkins会认为认为一直没完成

shell的日志输出

nohup /usr/local/java/jdk-21.0.7/bin/java -jar /root/xxoo/target/project-0.0.1-SNAPSHOT.jar >mylog.log 2>&1 &

运行前清理

当进行第二次构建时,测试服务器会应为之前构建的程序还在运行,端口也被占用,需要做运行前的清理、

在测试服务器的root目录下新建:x.sh文件

#!/bin/bash
​
#删除历史数据
rm -rf xxoo
​
appname=$1
#获取传入的参数
echo "arg:$1"
​
​
#获取正在运行的jar包pid
pid=`ps -ef | grep $1 | grep 'java -jar' | awk '{printf $2}'`
​
echo $pid
​
#如果pid为空,提示一下,否则,执行kill命令
if [ -z $pid ];
#使用-z 做空值判断
        then
                echo "$appname not started"
​
        else
               kill -9 $pid
                echo "$appname stoping...."
​
check=`ps -ef | grep -w $pid | grep java`
if [ -z $check ];
​
        then
                echo "$appname pid:$pid is stop"
        else
                echo "$appname stop failed"
​
fi
​
​
fi
​

在Item中配置Pre Steps
image-20250606195115148.png

此时就完成了配置

流程

  • 程序被提交至GitLab
  • 管理员进行代码合并
  • 在Jenkins中进行构建
  • 在测试服务器中查看运行效果

图说明

image-20250606195324364.png

最后修改:2025 年 06 月 06 日
如果觉得我的文章对你有用,请随意赞赏