1 Star 1 Fork 3

王涛 / jenkins入门

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MulanPSL-1.0

Jenkins 教程

1. 简介

1.1 介绍

 Jenkins是一个开源软件项目,是基于Java开发的一种持续集成工具,用于监控持续重复的工作,旨在提供一个开放易用的软件平台,使软件的持续集成变成可能。

我说下我以前开发的痛点,在一些中小型企业,每次开发一个项目完成后,需要打包部署,可能没有专门的运维人员,只能开发人员去把项目打成一个war包,可能这个项目已经上线了,需要把服务关,在部署到服务器上,将项目启动起来,这个时候可能某个用户正在操作某些功能上的东西,如果你隔三差五的部署一下,这样的话对用户的体验也不好,自己也是烦的很,总是打包拖到服务器上。希望小型企业工作人员学习一下,配置可能复杂,但是你配置好了之后,你只需要把代码提交到Git或者Svn上,自动构建部署,非常方便。有任何地方不懂的翻到最下方随时咨询我,想帮助更多的初学者共同一起努力成长!

1.2 环境准备

image-20210510095331698

1.2.1 安装jenkins

jenkins 镜像网站

https://mirrors.cloud.tencent.com/jenkins/
https://mirrors.huaweicloud.com/jenkins/
https://mirrors.tuna.tsinghua.edu.cn/jenkins/
http://mirrors.ustc.edu.cn/jenkins/

1) 离线安装

yum install -y java-1.8.0-openjdk* -y
wget https://mirrors.tuna.tsinghua.edu.cn/jenkins/redhat-stable/jenkins-2.277.4-1.1.noarch.rpm
rpm -ivh jenkins-2.277.4-1.1.noarch.rpm
yum install jenkins
systemctl start jenkins

2) docker 安装

安装docker

1.启动docker,下载Jenkins镜像文件

docker pull jenkins/jenkins

img

2.创建Jenkins挂载目录并授权权限(我们在服务器上先创建一个jenkins工作目录 /var/jenkins_mount,赋予相应权限,稍后我们将jenkins容器目录挂载到这个目录上,这样我们就可以很方便地对容器内的配置文件进行修改。 如果我们不这样做,那么如果需要修改容器配置文件,将会有点麻烦,因为虽然我们可以使用docker exec -it --user root 容器id /bin/bash 命令进入容器目录,但是连简单的 vi命令都不能使用)

mkdir -p /var/jenkins_mount
chmod 777 /var/jenkins_mount

3.创建并启动Jenkins容器

  -d 后台运行镜像

  -p 10240:8080 将镜像的8080端口映射到服务器的10240端口。

  -p 10241:50000 将镜像的50000端口映射到服务器的10241端口

  -v /var/jenkins_mount:/var/jenkins_mount /var/jenkins_home目录为容器jenkins工作目录,我们将硬盘上的一个目录挂载到这个位置,方便后续更新镜像后继续使用原来的工作目录。这里我们设置的就是上面我们创建的 /var/jenkins_mount目录

  -v /etc/localtime:/etc/localtime让容器使用和服务器同样的时间设置。

  --name myjenkins 给容器起一个别名

docker run -d -p 10240:8080 -p 10241:50000 -v /var/jenkins_mount:/var/jenkins_home -v /etc/localtime:/etc/localtime --name myjenkins jenkins/jenkins

img

自己的jenkins

mkdir ~/jenkins
mkdir  ~/jenkins/jenkins_mount
mkdir  ~/jenkins/etc
mkdir  ~/jenkins/maven
docker run -it -d -p 10240:8080 -p 10241:5000 -u root -v ~/jenkins/jenkins_mount:/var/jenkins_home -v /etc/localtime:/etc/localtime -v ~/jenkins/maven:/var/maven -v ~/jenkins/etc/:/etc/  --name myjenkins jenkins/jenkins:lts

4.查看jenkins是否启动成功,如下图出现端口号,就为启动成功了

docker ps -l

img

5.查看docker容器日志。

docker logs myjenkins

img

6.配置镜像加速,进入 cd /var/jenkins_mount/ 目录。

cd /var/jenkins_mount/

img

修改 vi hudson.model.UpdateCenter.xml里的内容

修改前

img

将 url 修改为腾讯云官方镜像:

https://mirrors.cloud.tencent.com/jenkins/updates/update-center.json

修改后

img

配置国内镜像源

mv /etc/apt/sources.list /etc/apt/sources.list.bak
echo "deb http://mirrors.163.com/debian/ jessie main non-free contrib" >/etc/apt/sources.list
echo "deb http://mirrors.163.com/debian/ jessie-proposed-updates main non-free contrib" >>/etc/apt/sources.list
echo "deb-src http://mirrors.163.com/debian/ jessie main non-free contrib" >>/etc/apt/sources.list
echo "deb-src http://mirrors.163.com/debian/ jessie-proposed-updates main non-free contrib" >>/etc/apt/sources.list
apt-get update

3) 访问jenkins

  1. 访问Jenkins页面,输入你的ip加上10240

img

  1. 管理员密码获取方法,编辑initialAdminPassword文件查看,把密码输入登录中的密码即可,开始使用。
vi /var/jenkins_mount/secrets/initialAdminPassword

img

  1. 到此以全部安装成功,尽情的使用吧!

img

1.2.2 安装gitlab

一、安装及配置

1.gitlab镜像拉取
# gitlab-ce为稳定版本,后面不填写版本则默认pull最新latest版本
$ docker pull gitlab/gitlab-ce

img

拉取镜像

2.运行gitlab镜像
docker run -d  -p 443:443 -p 80:80 -p 222:22 --name gitlab --restart always -v /home/gitlab/config:/etc/gitlab -v /home/gitlab/logs:/var/log/gitlab -v /home/gitlab/data:/var/opt/gitlab gitlab/gitlab-ce
# -d:后台运行
# -p:将容器内部端口向外映射
# --name:命名容器名称
# -v:将容器内数据文件夹或者日志、配置等文件夹挂载到宿主机指定目录

运行成功后出现一串字符串

img

运行成功

docker run -d  -p 443:443 -p 8088:80 -p 222:22 --name gitlab --restart always -v ~/gitlab/config:/etc/gitlab -v ~/gitlab/logs:/var/log/gitlab -v ~/gitlab/data:/var/opt/gitlab gitlab/gitlab-ce
3.配置

按上面的方式,gitlab容器运行没问题,但在gitlab上创建项目的时候,生成项目的URL访问地址是按容器的hostname来生成的,也就是容器的id。作为gitlab服务器,我们需要一个固定的URL访问地址,于是需要配置gitlab.rb(宿主机路径:/home/gitlab/config/gitlab.rb)。

# gitlab.rb文件内容默认全是注释
vim /home/gitlab/config/gitlab.rb

配置文件

# 配置http协议所使用的访问地址,不加端口号默认为80
external_url 'http://192.168.199.231'

# 配置ssh协议所使用的访问地址和端口
gitlab_rails['gitlab_ssh_host'] = '192.168.199.231'
gitlab_rails['gitlab_shell_ssh_port'] = 222 # 此端口是run时22端口映射的222端口
:wq #保存配置文件并退出

img

修改gitlab.rb文件

# 重启gitlab容器
docker restart gitlab

此时项目的仓库地址就变了。如果ssh端口地址不是默认的22,就会加上ssh:// 协议头 打开浏览器输入ip地址(因为我的gitlab端口为80,所以浏览器url不用输入端口号,如果端口号不是80,则打开为:ip:端口号)

4.创建一个项目

第一次进入要输入新的root用户密码,设置好之后确定就行

img

gitlab页面

下面我们就可以新建一个项目了,点击Create a project

img

Create a project

创建完成后:

img

创建完成!

二、用户使用

1.下载git.exe

双击git.exe安装git(一直点下一步,直到完成) 点击电脑桌面空白地方右键看到如下两行即安装成功

img

image.png

2.登录gitlab网页

urlhttp://192.168.1.111 填写账号密码登录

img

登录页面

3.设置ssh

1.打开本地git bash,使用如下命令生成ssh公钥和私钥对

ssh-keygen -t rsa -C 'xxx@xxx.com'

然后一路回车(-C 参数是你的邮箱地址)

img

生成密匙

2.然后输入命令:

# ~表示用户目录,比如我的windows就是C:\Users\Administrator,并复制其中的内容
cat ~/.ssh/id_rsa.pub

img

公匙

3.打开gitlab,找到Profile Settings-->SSH Keys--->Add SSH Key,并把上一步中复制的内容粘贴到Key所对应的文本框

img

img

添加公匙到gitlab

4.从gitlab克隆代码

1.回到gitlab页面点击projects->your projects

img

2.选择一个需要克隆的项目,进入

img

我的项目页面

3.点击按钮复制地址

img

复制ssh地址

4.新建一个文件夹,我在这里在我的电脑D盘下新建project文件夹

img

5.进入projects文件夹右键选择->Git Bash Here

img

点击Git Bash Here

6.设置用户名和邮箱

git config --global user.name "你的名字"
git config --global user.email "你的邮箱"

img

设置名字和邮箱

7.克隆项目

git clone 项目地址

img

克隆项目

8.查看projects文件夹,项目已经克隆下来了

img

项目目录

5.提交代码到gitlab

1.基于以上步骤,在克隆的项目文件夹下新增一个测试文件

img

新增txt文件

2.查看同步状态 在项目文件夹下右键点击->Git Bash Here

img

输入

git status

img

状态

可以看到红色部分有需要提交的文件 3.提交代码 输入

git add  测试提交的文件.txt

(“git add“后加“.”则添加全部文件,也可以加"*.txt"表示添加全部需要提交的txt文件 )

img

add需要提交的文件

然后输入以下命令提交并添加提交信息

git commit -m "message"

img

commit

最后输出以下命令提交到gitlab

git push origin master

img

1.2.3 gitlab占用内存太多问题

修改/etc/gitlab/gitlab.rb

unicorn['worker_processes'] = 2
postgresql['max_worker_processes'] = 4
nginx['worker_processes'] = 4

重新运行

gitlab-ctl reconfigure  #gitlab会读取配置文件参数并修改各个插件的配置文件去(我猜的)
gitlab-ctl restart

2. 入门

2.1 安装中文插件

image-20210510095033219

2.2 角色控制Role-Based Strategy

image-20210510102844184

点击"Manage Roles"

image-20210510102901425

进行角色的管理

image-20210510102914324

2.3 安装凭证

2.4 jenkins拉取项目

2.4.1 拉取gitlab 项目

1. 设置全局凭据

image-20210510103928691

点击添加凭据

image-20210510104120595

输入Gitee 账号、密码 ID可以任意填写,描述框可以根据项目来撰写 在这里插入图片描述

类型项一定要选择

在这里插入图片描述

2. 新建Item

Jenkins首页—Item—新建 也可以进入到已有的Item里,再新建一个Item

在这里插入图片描述

输入项目名称,一般用项目名称来命名,然后选择流水线,确定

在这里插入图片描述

项目创建完毕

image-20210510104546158

3. 具体任务配置

Jenkins首页—相应Item—配置----流水线—址—生成流水线脚本

在这里插入图片描述

#去gitee克隆代码地址

在这里插入图片描述

配置在Jenkins上

在这里插入图片描述

在这里插入图片描述

复制脚本

在这里插入图片描述

#这下面是配置构建脚本,注意Jenkins支持任何语言编写的项目的构建 在这里插入图片描述

粘贴需要构建的代码链接和要执行的ssh命令,建议每次构建都加上ls -l 验证是否成功,应用 保存

在这里插入图片描述

4、构建验证

进入任务,点击立即构建,成功的话会显示绿色,可以在Build History验证是否成功

在这里插入图片描述

点击任务,进入任务页面,选择控制台输出,可以看到构建的详细日志,如果构建失败,可以在日志中查看失败原因: 在这里插入图片描述

2.4.2 拉取gitee 项目

1. 安装gitee 插件

image-20210510104930930

2. 添加Gitee链接配置

前往 Jenkins -> Manage Jenkins -> Configure System -> Gitee Configuration -> Gitee connections

image-20210510105938146

点击进行数据的配置

image-20210510105954742

Connection name 中输入 Gitee 或者你想要的名字

Gitee host URL 中输入Gitee完整 URL地址: https://gitee.com (Gitee私有化客户输入部署的域名)

Credentials中如还未配置Gitee APIV5 私人令牌,点击Add ->Jenkins

  1. Domain 选择 Global credentials
  2. Kind 选择 Gitee API Token
  3. Scope 选择你需要的范围
  4. Gitee API Token 输入你的Gitee私人令牌,获取地址:https://gitee.com/profile/personal_access_tokens
  5. ID, Descripiton 中输入你想要的 ID 和描述即可。

image-20210510110612637

  1. Credentials 选择配置好的 Gitee APIV5 Token

  2. 点击 Advanced ,可配置是否忽略 SSL 错误(视您的Jenkins环境是否支持),并可设置链接测超时时间(视您的网络环境而定)

  3. 点击 Test Connection 测试链接是否成功,如失败请检查以上 3,5,6 步骤。

image-20210510110655803

配置成功后如图所示: Gitee链接配置

3. 新建构建任务

前往 Jenkins -> New Item , name 输入 'Gitee Test',选择 Freestyle project 保存即可创建构建项目。

4. 任务全局配置

任务全局配置中需要选择前一步中的Gitee链接。前往某个任务(如'Gitee Test')的 Configure -> General,Gitee connection 中选择前面所配置的Gitee链接,如图:

image-20210510111209353

2.5 安装maven

2.6 安装tomcat

安装jdk

yum install -y java-1.8.0-openjdk* -y

安装tomcat

mkdir tomcat
cd tomcat
wget https://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-10/v10.0.6/bin/apache-tomcat-10.0.6.tar.gz
tar -zxvf apache-tomcat-10.0.6.tar.gz

编辑用户信息

vim apache-tomcat-10.0.6//conf/tomcat-users.xml

设置用户信息

<tomcat-users>
   <role rolename="tomcat"/> 
   <role rolename="role1"/>
   <role rolename="manager-script"/> 
   <role rolename="manager-gui"/>
   <role rolename="manager-status"/>
   <role rolename="admin-gui"/>
   <role rolename="admin-script"/> 
   <user username="tomcat" password="tomcat" roles="manager-gui,manager- script,tomcat,admin-gui,admin-script"/> 
</tomcat-users>

开放外网访问权限

vim webapps/manager/META-INF/context.xml

注释信息

image-20210518154402642

<!-- 
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /> 
-->

修改端口号--看需求

vim conf/server.xml

修改完配置为

image-20210518154843683

开启tomcat

./startup.sh

image-20210518155025222

输入tomcat,密码tomcat

image-20210518155050999

进入管理界面

image-20210518155250939

3. jenkins 风格类型

3.1 自由风格类型

拉取代码->编译->打包->部署

3.1.1 拉取代码

image-20210518160244635

3.1.2 编译

构建->添加构建步骤->Executor Shell

image-20210518160456620

echo "开始编译和打包" 
mvn clean package 
echo "编译和打包结束"

image-20210518160557558

这个时候会报错,

image-20210518161038144

解决方法

echo $PATH

复制path 路径,点击全局配置,添加全局属性

image-20210518161757355

3.1.3 部署

把项目部署到远程的Tomcat里面

安装 Deploy to container插件

点击构建后操作

image-20210518162545887

添加tomcat 的凭证

image-20210519101442247

构件后操作

image-20210519101503486

就可以打包成功

3.2 Maven 风格类型

3.2.1 安装Maven Integration插件

image-20210519111628230

3.2.2 创建Maven项目

image-20210519111646577

3.2.3 配置项目

image-20210519111712992

3.3 流水线风格类型

Pipeline 脚本是由 Groovy 语言实现的,但是我们没必要单独去学习 Groovy

Pipeline 支持两种语法:Declarative(声明式)和 Scripted Pipeline(脚本式)语法

Pipeline 也有两种创建方法:可以直接在 Jenkins 的 Web UI 界面中输入脚本;也可以通过创建一

个 Jenkinsfifile 脚本文件放入项目源码库中(一般我们都推荐在 Jenkins 中直接从源代码控制(SCM)

中直接载入 Jenkinsfifile Pipeline 这种方法)。

3.3.1 安装pipline

image-20210519160939109

3.3.2 创建项目

image-20210519161009364

3.3.3 拉取代码

image-20210519161033183

自定义流水线

image-20210519161120562

构建流水线语法

image-20210519162445601

拉取代码

image-20210519162647350

生成pipline 代码

image-20210519162806786

构件代码

pipeline {
    agent any

    stages {
        stage('pull code') {
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[credentialsId: '1527f9a8-f6ed-41b3-93a7-c05a88f36de9', url: 'https://gitee.com/fakerlove/clock']]])
            }
        }
          stage('build project') {
            steps {
               sh 'mvn clean package'
            }
        }
          stage("sa") {
            steps {
                echo 'goujian构件wancheng'
            }
        }
    }
    
}

3.3.4 构建成功

image-20210519161212583

3.4 jenkins 常见的触发器

jenkins 常见触发器

image-20210519170109920

其中gitee为安装了gitee 插件后,出现的触发

默认有4种

  • 触发远程构建
  • 轮训SCM
  • 其他工程构建后触发
  • 定时构建

3.4.1 gitee 触发器

gitee 设置签发文章

https://gitee.com/help/articles/4193#article-header9

在jenkins 上设置触发器,点击生成秘钥

image-20210519171306631

gitee设置webHook

image-20210519171342064

修改代码,提交至gitee,jenkins立即进行了刷新测试

image-20210519171638974

3.4.2 触发远程构建

设置token信息

image-20210519171843116

输入网址即可进行触发

http://192.168.66.101:8888/job/web_demo_pipeline/build?token=6666

3.4.3 其他工程创建触发

创建pre_job流水线工程

image-20210519173346089

配置需要触发的工程

image-20210519173408602

3.4.4 定时构建

image-20210519173428203

每30分钟构建一次:H代表形参 H/30 * * * * 10:02 10:32

每2个小时构建一次: H H/2 * * *

每天的8点,12点,22点,一天构建3次: (多个时间点中间用逗号隔开) 0 8,12,22 * * *

每天中午12点定时构建一次 H 12 * * *

每天下午18点定时构建一次 H 18 * * *

在每个小时的前半个小时内的每10分钟 H(0-29)/10 * * * *

每两小时一次,每个工作日上午9点到下午5点(也许是上午10:38,下午12:38,下午2:38,下午

4:38) H H(9-16)/2 * * 1-5

3.4.5 参数化构建

3.5 邮件发送

3.5.1 安装插件

image-20210520102548901

3.5.2 开启邮箱支持

开启权限

image-20210520103028041

点击生成授权码

image-20210520103307250

发送配置短信,发送完成后,点击我已发送、获取密码

image-20210520103323603

3.5.3 配置

配置邮件管理员

image-20210520105311778

配置Extended

image-20210520105355585

配置 jenkins 默认邮箱

image-20210520105543453

点击测试

image-20210520105600860

在项目的根目录下创建email.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>${ENV, var="JOB_NAME"}-第${BUILD_NUMBER}次构建日志</title>
</head>
<body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4" offset="0">
<table width="95%" cellpadding="0" cellspacing="0"
       style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans- serif">
    <tr>
        <td>(本邮件是程序自动下发的,请勿回复!)</td>
    </tr>
    <tr>
        <td>
            <h2>
                <span style="color: #0000FF; ">构建结果 - ${BUILD_STATUS}</span>
            </h2>
        </td>
    </tr>
    <tr>
        <td><br/> <b><span style="color: #0B610B; ">构建信息</span></b>
            <hr size="2" width="100%" align="center"/>
        </td>
    </tr>
    <tr>
        <td>
            <ul>
                <li>项目名称&nbsp;&nbsp;${PROJECT_NAME}</li>
                <li>构建编号&nbsp;&nbsp;第${BUILD_NUMBER}次构建</li>
                <li>触发原因:&nbsp;${CAUSE}</li>
                <li>构建日志:&nbsp;<a href="${BUILD_URL}console">${BUILD_URL}console</a></li>
                <li>构建&nbsp;&nbsp;Url&nbsp;&nbsp;<a href="${BUILD_URL}">${BUILD_URL}</a></li>
                <li>工作目录&nbsp;&nbsp;<a href="${PROJECT_URL}ws">${PROJECT_URL}ws</a></li>
                <li>项目&nbsp;&nbsp;Url&nbsp;&nbsp;<a href="${PROJECT_URL}">${PROJECT_URL}</a></li>
            </ul>
        </td>
    </tr>
    <tr>
        <td><b><span style="color: #0B610B; ">Changes Since Last Successful Build:</span></b>
            <hr size="2" width="100%" align="center"/>
        </td>
    </tr>
    编写Jenkinsfile添加构建后发送邮件
    <tr>
        <td>
            <ul>
                <li>历史变更记录 : <a href="${PROJECT_URL}changes">${PROJECT_URL}changes</a></li>
            </ul>
            ${CHANGES_SINCE_LAST_SUCCESS,reverse=true, format="Changes for Build #%n:<br/>%c<br/>",showPaths=true,changesFormat="
            <pre>[%a]<br/>%m</pre>
            ",pathFormat="&nbsp;&nbsp;&nbsp;&nbsp;%p"}
        </td>
    </tr>
    <tr>
        <td><b>Failed Test Results</b>
            <hr size="2" width="100%" align="center"/>
        </td>
    </tr>
    <tr>
        <td>
            <pre style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif">$FAILED_TESTS</pre>
            <br/>
        </td>
    </tr>
    <tr>
        <td>
            <b>
                <span style="color: #0B610B; ">构建日志 (最后 100行):</span>
            </b>
            <hr size="2" width="100%" align="center"/>
        </td>
    </tr>
    <tr>
        <td>
            <textarea cols="80" rows="30" readonly="readonly" style="font-family: Courier New">
                ${BUILD_LOG, maxLines=100}
            </textarea>
        </td>
    </tr>
</table>
</body>
</html>

image-20210520110622468

修改流水线的语法,在最后添加pipline 语法

pipeline {
    agent any

    stages {
        stage('pull code') {
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[credentialsId: '1527f9a8-f6ed-41b3-93a7-c05a88f36de9', url: 'https://gitee.com/fakerlove/clock']]])
            }
        }
          stage('build project') {
            steps {
               sh 'mvn clean package'
            }
        }
          stage("sa") {
            steps {
                echo 'goujian构件wancheng'
            }
        }
    }
    post { 
        always {
            emailext(
                subject: '构建通知:${PROJECT_NAME} - Build # ${BUILD_NUMBER} - ${BUILD_STATUS}!', 
                body: '${FILE,path="email.html"}', 
                to: '203462009@qq.com' ) 
        }
    }
}

点击重新构建,构建完成后,会接收到邮件信息

image-20210520112034362

3.6 SonarQube 代码审查

4. Docker+SpringCloud

4.1 环境准备

image-20210520163648458

  • docker
  • jenkins
  • maven
  • harbor 私有的镜像仓库

4.1.1 docker的安装

centos 7

yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
yum install -y yum-utils
yum-config-manager \
    --add-repo \
    http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum makecache fast
yum install docker-ce docker-ce-cli containerd.io -y
systemctl start docker
docker version

centos 8

yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
yum install -y yum-utils
yum makecache 
yum install -y wget
wget -O /etc/yum.repos.d/CenOS-Base.repo https://mirrors.aliyun.com/repo/Centos-8.repo
yum clean all
yum install -y https://download.docker.com/linux/centos/8/x86_64/stable/Packages/containerd.io-1.4.3-3.1.el8.x86_64.rpm
yum install docker-ce docker-ce-cli -y
systemctl start docker
docker version

容器镜像加速

sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://ip92h4jn.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

4.1.2 docker-compose 安装

compose 网址

https://github.com/docker/compose/releases

安装docker-compose

sudo curl -L "https://gitee.com/fakerlove/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
docker-compose --version

centos7 可以选择如下安装

yum -y install python-pip
pip install --upgrade pip
pip install docker-compose
docker-compose -version

4.1.3 harbor 安装

在github 上找到适合自己的版本

https://github.com/goharbor/harbor/tags

最低的需求配置

image-20210520151346044

上传下载的软件,并解压

 tar -zxvf harbor-offline-installer-v2.2.2.tgz -C /usr/local/

复制yml

cd /usr/local/harbor/
cp harbor.yml.tmpl harbor.yml
vim harbor.yml

修改一下三个部分信息

image-20210521212145966

启动脚本

./install.sh

image-20210520161403576

等启动成功,输入网址

http://121.37.175.163/

image-20210520161615617

如果默认80 网址,有服务,即可修改端口信息

image-20210520161626732

4.1.4 Harbor 使用

创建harbor项目

image-20210521094535809

创建镜像,给镜像把tag

121.37.175.163 为Harbor的网址,jenkins为Harbor的用户信息,myjenkins 为镜像名字

注意点

80端口的话,打tag 时不能添加80,直接就是ip 地址即可,其中clock 为项目名。kk 为在仓库中镜像的名字

docker tag jenkins/jenkins:latest 121.37.175.163/clock/kk:1.0

image-20210521213410151

添加受信任名单

image-20210521095547573

vim /etc/docker/daemon.json

添加一下内容

{
  "registry-mirrors": ["https://ip92h4jn.mirror.aliyuncs.com"],
  "insecure-registries": ["121.37.175.163:80"]
}

使用Harbor 账户登录docker

systemctl daemon-reload
systemctl restart docker
docker login 121.37.175.163 -u admin -p 123456

上传镜像

docker push  121.37.175.163/clock/kk:1.0

image-20210522115421027

如果报错

Get http://harbor.phc-dow.com/v2/: Get http://harbor.phc-dow.com:180/service/token?account=admin&client_id=docker&offline_token=true&service=harbor-registry: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers) (Client.Timeout exceeded while awaiting headers)

解决方案

  1. 检查是否添加信任名单,
  2. 检查是否填写外网网址
  3. 检查用户名和密码
  4. 检查端口号,是否填写正确
  5. 检查防火墙和安全组是否开放

最后试试以下内容

vim /etc/sysctl.conf
net.ipv4.ip_forward = 1 #最后一行写入
sysctl -p

4.2 使用DockerFile插件生成镜像

4.2.1添加打包插件

  <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>dockerfile-maven-plugin</artifactId>
                <version>1.4.13</version>
                <configuration>
                    <repository>${project.artifactId}</repository>
                    <buildArgs>
                        <JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
                    </buildArgs>
                </configuration>
            </plugin>

4.2.2 编写Dockerfile 文件

FROM openjdk:8-jdk-alpine
EXPOSE 8081
ARG JAR_FILE
ADD ${JAR_FILE} /app.jar
ENTRYPOINT ["java", "-jar","/app.jar"]

image-20210522170028697

修改jenkins 信息

4.2.3 打包镜像,并上传服务器

可以使用阿里云的镜像容器服务,或者自己的harbor私人镜像仓库

使用流水线语法,进行上传服务

image-20210523095155330

pipeline {
    agent any
    environment {
        tag = 'latest'
        //阿里云的镜像存储空间
        harbor_url = 'registry.cn-shanghai.aliyuncs.com'
        //镜像存储的命名空间
        harbor_project_name = 'jokerak' //Harbor的凭证
        harbor_auth = 'ef499f29-f138-44dd-975e-ff1ca1d8c933'
        // 项目名
        project_name = 'clock'

        imageName = "${project_name}:${tag}"
    }

    stages {
        stage('拉取代码') {
            steps {
                checkout([
                            $class: 'GitSCM',
                            branches: [[name: '*/master']],
                            extensions: [],
                            userRemoteConfigs:
                            [[credentialsId:
                            '1527f9a8-f6ed-41b3-93a7-c05a88f36de9',
                            url: 'https://gitee.com/fakerlove/clock']
                            ]
                       ])
            }
        }
        stage('打包编译项目,创建镜像,上传镜像') {
            steps {
                // 打包编译项目
                sh 'mvn clean package dockerfile:build'

                // 给镜像打tag
                sh "docker tag ${imageName} ${harbor_url}/${harbor_project_name}/${imageName}"

                withCredentials([usernamePassword(credentialsId: '5b07edf3-bfb8-49e7-8b27-a6d600ef99d8', passwordVariable: 'password', usernameVariable: 'username')]) {
                    // 登录镜像
                    sh "docker login -u ${username} -p ${password} ${harbor_url}"
                    //上传镜像
                    sh "docker push ${harbor_url}/${harbor_project_name}/${imageName}"
                }
            }
        }
    }
    post {
        always {
            // 发送邮件
            emailext(
                subject: '构建通知:${PROJECT_NAME} - Build # ${BUILD_NUMBER} - ${BUILD_STATUS}!',
                body: '${FILE,path="email.html"}',
                to: '203462009@qq.com' )
        }
    }
}

4.2.4 拉取镜像并部署

1) 安装插件

安装以下插件,可以实现远程发送Shell命令

image-20210523095613420

首先在jenkins 所在服务器下生成ssh ,2.277 版本一下不支持一下生成公钥。不知道现在2.932 还支不支持

ssh-keygen -o

可以试一下

ssh-keygen -m PEM -t rsa -b 4096

说明:

-m 参数指定密钥的格式,PEM是rsa之前使用的旧格式
 -b 指定密钥长度。对于RSA密钥,最小要求768位,默认是2048位。

拷贝公钥到服务器中

ssh-copy-id 121.37.175.163

image-20210523100212577

2) 添加远程服务器

系统配置->添加远程服务器

修改公钥权限,复制公钥值jenkins目录下,以防没有权限访问

mkdir /var/lib/jenkins/.ssh
cp /root/.ssh/* /var/lib/jenkins/.ssh/

image-20210523101501916

点击测试

image-20210523161243920

3) 上传代码

使用流水线语法生成器

创建流水线语法

  sshPublisher(
                    publishers:
                [sshPublisherDesc(configName: '华为云服务器',
                transfers: [
                    sshTransfer(
                        cleanRemote: false,
                        excludes: '',
                        execCommand: "/opt/jenkins_shell/deploy.sh $harbor_url $harbor_project_name $project_name $tag $port",
                        execTimeout: 120000,
                        flatten: false,
                        makeEmptyDirs: false,
                        noDefaultExcludes: false,
                        patternSeparator: '[, ]+',
                        remoteDirectory: '',
                        remoteDirectorySDF: false,
                        removePrefix: '',
                        sourceFiles: '')],
                        usePromotionTimestamp: false,
                        useWorkspaceInPromotion: false,
                        verbose: false)])

在部署服务的服务器上创建deploy.sh

#! /bin/sh #接收外部参数 
harbor_url=$1 
harbor_project_name=$2 
project_name=$3 
tag=$4 
port=$5 
imageName=$harbor_url/$harbor_project_name/$project_name:$tag 
echo "$imageName" #查询容器是否存在,存在则删除 
containerId=`docker ps -a | grep -w ${project_name}:${tag} | awk '{print $1}'` 
if [ "$containerId" != "" ] ; then 
#停掉容器 
  docker stop $containerId 
#删除容器 
  docker rm $containerId 
  echo "成功删除容器"
fi
#查询镜像是否存在,存在则删除 
imageId=`docker images | grep -w $project_name | awk '{print $3}'`
if [ "$imageId" != "" ] ; then 
#删除镜像 
 docker rmi -f $imageId
 echo "成功删除镜像" 
fi
# 登录Harbor私服 
docker login -u itcast -p Itcast123 $harbor_url 
# 下载镜像 
docker pull $imageName 
# 启动容器 
docker run -di -p $port:$port -v /etc/localtime:/etc/localtime $imageName
echo "容器启动成功"

4.2.5 出现的错误如下

  1. 找不到打包插件

    更换maven 镜像

    	<mirror>
    			<id>
    				alimaven
    			</id>
    			
    			<mirrorOf>
    				*
    			</mirrorOf>
    			
    			<name>
    				aliyun maven
    			</name>
    			
    			<url>
    				https://maven.aliyun.com/repository/public
    			</url>
    		</mirror>
  2. 无法创建maven包

    修改maven 仓库权限

    chmod 777 /var/lib/res
  3. Jenkins: unix://localhost:80: Permission denied

    chmod 777 /var/run/docker.sock

4.2.6 流水线的总代码

pipeline {
    agent any
    environment {
        tag = 'latest'
        //阿里云的镜像存储空间
        harbor_url = 'registry.cn-shanghai.aliyuncs.com'
        //镜像存储的命名空间
        harbor_project_name = 'jokerak' //Harbor的凭证
        harbor_auth = 'ef499f29-f138-44dd-975e-ff1ca1d8c933'
        // 项目名
        project_name = 'clock'
        port = '8081'
        imageName = "${project_name}:${tag}"
    }

    stages {
        stage('拉取代码') {
            steps {
                checkout([
                            $class: 'GitSCM',
                            branches: [[name: '*/master']],
                            extensions: [],
                            userRemoteConfigs:
                            [[credentialsId:
                            '1527f9a8-f6ed-41b3-93a7-c05a88f36de9',
                            url: 'https://gitee.com/fakerlove/clock']
                            ]
                       ])
            }
        }
        stage('打包编译项目,创建镜像,上传镜像') {
            steps {
                // 打包编译项目
                sh 'mvn clean package dockerfile:build'

                // 给镜像打tag
                sh "docker tag ${imageName} ${harbor_url}/${harbor_project_name}/${imageName}"

                withCredentials([usernamePassword(credentialsId: '5b07edf3-bfb8-49e7-8b27-a6d600ef99d8', passwordVariable: 'password', usernameVariable: 'username')]) {
                    // 登录镜像
                    sh "docker login -u ${username} -p ${password} ${harbor_url}"
                    //上传镜像
                    sh "docker push ${harbor_url}/${harbor_project_name}/${imageName}"
                }
            }
        }
        stage('拉取镜像,部署服务') {
            steps {
                sshPublisher(
                    publishers:  [
                     sshPublisherDesc(
                     configName: 'cloud',
                     transfers: [
                      sshTransfer(
                        cleanRemote: false,
                        excludes: '',
                        execCommand: "/opt/jenkins_shell/deploy.sh $harbor_url $harbor_project_name $project_name $tag $port",
                        execTimeout: 120000,
                        flatten: false,
                        makeEmptyDirs: false,
                        noDefaultExcludes: false,
                        patternSeparator: '[, ]+',
                        remoteDirectory: '',
                        remoteDirectorySDF: false,
                        removePrefix: '',
                        sourceFiles: '')],
                        usePromotionTimestamp: false,
                        useWorkspaceInPromotion: false,
                        verbose: false)])
            }
        }
    }
    post {
        always {
            // 发送邮件
            emailext(
                subject: '构建通知:${PROJECT_NAME} - Build # ${BUILD_NUMBER} - ${BUILD_STATUS}!',
                body: '${FILE,path="email.html"}',
                to: '203462009@qq.com' )
        }
    }
}

4.3 部署静态网站

4.3.1 安装ngnix

yum install epel-release
yum -y install nginx

修改配置文件,修改端口信息

vi /etc/nginx/nginx.conf

image-20210524103241829

要关闭selinux

vi /etc/selinux/config

永久关闭 SELINUX=disabled

image-20210524103436326

启动ngnix

systemctl start nginx

image-20210524103555607

4.3.2 安装nodejs 插件

搜索插件NodeJS

image-20210524104356108

4.3.3 安装nodejs

尽量使用自己的npm,因为需要配置镜像,自己的环境搭建起来

wget https://npm.taobao.org/mirrors/node/v14.16.1/node-v14.16.1-linux-x64.tar.xz
xz -d node-v14.16.1-linux-x64.tar.xz
tar -xvf node-v14.16.1-linux-x64.tar
mkdir -p  /var/lib/node 
rm -rf /var/lib/node/*
cp ~/node-v14.16.1-linux-x64/* /var/lib/node -r
chmod 777 -R /var/lib/node
ln -s /var/lib/node/bin/node /usr/bin/node
ln -s /var/lib/node/bin/npm /usr/bin/npm
npm config set registry https://registry.npm.taobao.org
vim /etc/profile
export PATH=/var/lib/node/bin:$PATH
source /etc/profile

image-20210524145722467

4.3.4 创建项目

一定要修改连接的根目录,不然会出现问题

image-20210524153948557

创建一个Vue的项目。vue-cli3 脚手架创建项目。然后创建Jenkinsfile 文件

在流水线语法生成器,生成语法

image-20210524145646139

4.3.5 Jenkinsfile 代码

4.4 SpringCloud 打包服务

注意点

  • common 工程中,不能够使用springboot 的打包插件,必须移除common 父工程的打包插件

使用,-f 指定特定工程进行打包

mvn -f common clean install

image-20210524190538534

4.4.1 修改配置

# 集群版
spring:
  application:
    name: EUREKA-HA
---
server:
  port: 10086
spring: # 指定profile=eureka-server1
  profiles: eureka-server1
eureka:
  instance: # 指定当profile=eureka-server1时,主机名是eureka-server1
    hostname: 192.168.66.103
  client:
    service-url: # 将自己注册到eureka-server1、eureka-server2这个Eureka上面去
      defaultZone: http://192.168.66.103:10086/eureka/,http://192.168.66.104:10086/eureka/
      
---

server:
 port: 10086
spring:
 profiles: eureka-server2
eureka:
 instance:
  hostname: 192.168.66.104
 client:
  service-url:
   defaultZone: http://192.168.66.103:10086/eureka/,http://192.168.66.104:10086/eureka/

4.4.2 安装插件

安装Extended Choice Parameter

木兰宽松许可证, 第1版 木兰宽松许可证, 第1版 2019年8月 http://license.coscl.org.cn/MulanPSL 您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第1版(“本许可证”)的如下条款的约束: 0. 定义 “软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。 “贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。 “法人实体”是指提交贡献的机构及其“关联实体”。 “关联实体”是指,对“本许可证”下的一方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。 “贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。 1. 授予版权许可 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。 2. 授予专利许可 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括仅因您或他人修改“贡献”或其他结合而将必然会侵犯到的专利权利要求。如您或您的“关联实体”直接或间接地(包括通过代理、专利被许可人或受让人),就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。 3. 无商标许可 “本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。 4. 分发限制 您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。 5. 免责声明与责任限制 “软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。 条款结束。 如何将木兰宽松许可证,第1版,应用到您的软件 如果您希望将木兰宽松许可证,第1版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步: 1, 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字; 2, 请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中; 3, 请将如下声明文本放入每个源文件的头部注释中。 Copyright (c) [2019] [name of copyright holder] [Software Name] is licensed under the Mulan PSL v1. You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details. Mulan Permissive Software License,Version 1 Mulan Permissive Software License,Version 1 (Mulan PSL v1) August 2019 http://license.coscl.org.cn/MulanPSL Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v1 (this License) with following terms and conditions: 0. Definition Software means the program and related documents which are comprised of those Contribution and licensed under this License. Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License. Legal Entity means the entity making a Contribution and all its Affiliates. Affiliates means entities that control, or are controlled by, or are under common control with a party to this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity. Contribution means the copyrightable work licensed by a particular Contributor under this License. 1. Grant of Copyright License Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not. 2. Grant of Patent License Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed, excluding of any patent claims solely be infringed by your or others’ modification or other combinations. If you or your Affiliates directly or indirectly (including through an agent, patent licensee or assignee), institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken. 3. No Trademark License No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in section 4. 4. Distribution Restriction You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software. 5. Disclaimer of Warranty and Limitation of Liability The Software and Contribution in it are provided without warranties of any kind, either express or implied. In no event shall any Contributor or copyright holder be liable to you for any damages, including, but not limited to any direct, or indirect, special or consequential damages arising from your use or inability to use the Software or the Contribution in it, no matter how it’s caused or based on which legal theory, even if advised of the possibility of such damages. End of the Terms and Conditions How to apply the Mulan Permissive Software License,Version 1 (Mulan PSL v1) to your software To apply the Mulan PSL v1 to your work, for easy identification by recipients, you are suggested to complete following three steps: i. Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner; ii. Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package; iii. Attach the statement to the appropriate annotated syntax at the beginning of each source file. Copyright (c) [2019] [name of copyright holder] [Software Name] is licensed under the Mulan PSL v1. You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details.

简介

jenkins入门到精通 展开 收起
MulanPSL-1.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/vojx/getting-started-with-jenkins.git
git@gitee.com:vojx/getting-started-with-jenkins.git
vojx
getting-started-with-jenkins
jenkins入门
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891