怎么在欧美做网站推广,西宁做网站公司排名,重庆建站模板代理,如何搭建网络论坛平台Jenkins
Jenkins#xff0c;原名 Hudson#xff0c;2011 年改为现在的名字。它是一个开源的实现持续集成的软件工具。
官方网站#xff08;英文#xff09;#xff1a;https://www.jenkins.io/ 官方网站#xff08;中文#xff09;#xff1a;https://www.jenkins.io…Jenkins
Jenkins原名 Hudson2011 年改为现在的名字。它是一个开源的实现持续集成的软件工具。
官方网站英文https://www.jenkins.io/ 官方网站中文https://www.jenkins.io/zh/ 我们需要三台服务器
服务器名ip准备条件Jenkins-GitLab-ssh192.168.119.134至少4C、5GJenkins-Server192.168.119.135安装jdk1.8TestServer192.168.119.129安装jdk1.8
1、GitLab安装使用
官方网站https://about.gitlab.com/
安装所需最小配置
内存至少4G
https://docs.gitlab.cn/jh/install/requirements.html
1.1、在ssh下安装
官方安装文档https://gitlab.cn/install/?versionce
1.1.0、配置阿里云yum源
要配置阿里云的 Yum 源以下是在 CentOS 7 上的具体步骤 备份现有的 Yum 配置可选 在修改 Yum 配置之前建议备份当前的 Yum 配置文件以防意外情况。 sudo cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup下载阿里云的 Yum 配置文件 使用 curl 命令下载适合 CentOS 7 的阿里云 Yum 配置文件。 sudo curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo这将从阿里云下载 CentOS 7 的 Yum 配置文件并保存到 /etc/yum.repos.d/ 目录中。 清理 Yum 缓存并生成缓存 下载完配置文件后清理旧的 Yum 缓存并重新生成缓存。 sudo yum clean all
sudo yum makecache这将确保 Yum 使用新的阿里云镜像源。 验证 Yum 配置是否生效 运行 yum repolist 命令来查看 Yum 配置是否正确生效并列出可用的软件包仓库。 yum repolist如果列表显示来自阿里云的镜像源那么配置就生效了。
1.1.1、安装依赖
sudo yum install -y curl policycoreutils-python openssh-server perl
sudo systemctl enable sshd
sudo systemctl start sshd1.1.2、配置镜像
curl -fsSL https://packages.gitlab.cn/repository/raw/scripts/setup.sh | /bin/bash1.1.3、开始安装
sudo EXTERNAL_URLhttp://192.168.119.134 yum install -y gitlab-jh除非您在安装过程中指定了自定义密码否则将随机生成一个密码并存储在 /etc/gitlab/initial_root_password 文件中(出于安全原因24 小时后此文件会被第一次 gitlab-ctl reconfigure 自动删除因此若使用随机密码登录建议安装成功初始登录成功之后立即修改初始密码。使用此密码和用户名 root 登录。
1.1.4、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 # 查看日志1.2、在docker下安装
https://docs.gitlab.cn/jh/install/docker.html 安装所需最小配置
内存至少4G系统内核至少在3.10以上 uname -r 命令可查看系统内核版本
1.2.1、安装docker 更新yum源 yum update安装依赖 yum install -y yum-utils device-mapper-persistent-data lvm2添加镜像 #国外镜像
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
#阿里镜像
https://mirrors.aliyun.com/docker-ce/linux/centos/gpg
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo查看源中可使用版本 yum list docker-ce --showduplicates | sort -r安装指定版本 yum install docker配置开机启动项 systemctl start docker
systemctl enable docker
docker version1.2.2、使用容器安装gitlab
1.添加容器
docker run --detach \--hostname 192.168.119.134 \--publish 443:443 --publish 80:80 \--name gitlab \--restart always \--volume $GITLAB_HOME/config:/etc/gitlab:Z \--volume $GITLAB_HOME/logs:/var/log/gitlab:Z \--volume $GITLAB_HOME/data:/var/opt/gitlab:Z \--shm-size 256m \registry.gitlab.cn/omnibus/gitlab-jh:latest2.启动容器
docker start gitlab3.查看已存在的容器
docker ps -a4.进入容器
docker exec -it gitlab /bin/bash1.2.3、访问
http://192.168.119.134
当首次运行出现502错误的时候排查两个原因
虚拟机内存至少需要4g稍微再等等刷新一下可能就好了
1.2.4、管理员账号登录
用户名root
密码存在下面文件中登录后需要改密码不然24小时之后会失效
cat /etc/gitlab/initial_root_password登录成功之后
修改root用户密码 根据新的账号root、密码Wts123456 再次登录然后把gitLab切换成中文
1.3、创建一个项目
点击创建项目 填写项目名称选择项目URL、选择可见性级别点击创建项目 效果
2、Jenkins安装
官方文档介绍非常详细
官方网站英文https://www.jenkins.io/官方网站中文https://www.jenkins.io/zh/
安装需求
机器要求256 MB 内存建议大于 512 MB10 GB 的硬盘空间用于 Jenkins 和 Docker 镜像需要安装以下软件Java 8 ( JRE 或者 JDK 都可以)Docker 导航到网站顶部的Get Docker链接以访问适合您平台的Docker下载2.1、安装JDK
2.1.1、安装JRE 检索可用包 yum search java|grep jdk安装 yum install java-1.8.0-openjdk测试 [rootlocalhost ~]# java -version
openjdk version 1.8.0_412
OpenJDK Runtime Environment (build 1.8.0_412-b08)
OpenJDK 64-Bit Server VM (build 25.412-b08, mixed mode)默认yum安装java的时候会显示安装的是openjdk1.8 实则实际上只安装了jre
2.1.2、安装JDK
安装yum install -y java-devel结果 javahome配置(可选) 配置profile文件 编辑profile配置文件: vim /etc/profile [rootlocalhost ~]# vi /etc/profile我们当前jdk的路径在/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.412.b08-1.el7_9.x86_64 输入i进入编辑模式,在最下面补充配置信息,补充完后按Esc退出编辑模式后,输入:wq进行保存并退出 export JAVA_HOME/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.412.b08-1.el7_9.x86_64
export JRE_HOME${JAVA_HOME}/jre
export CLASSPATH.:${JAVA_HOME}/lib:${JRE_HOME}/lib:$CLASSPATH
export JAVA_PATH${JAVA_HOME}/bin:${JRE_HOME}/bin
export PATH$PATH:${JAVA_PATH} 配置文件生效 source /etc/profile查看JDK版本信息: java -version2.2、Maven安装
官网https://maven.apache.org/
2.2.1、安装
下载后复制到Jenkins所在服务器解压缩即可
[rootlocalhost ~]# tar -zxvf apache-maven-3.8.6-bin.tar.gz[rootlocalhost ~]# mv apache-maven-3.8.6 /usr/local/maven[rootlocalhost ~]# /usr/local/maven/bin/mvn[rootlocalhost ~]# /usr/local/maven/bin/mvn -v
Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63)
Maven home: /usr/local/maven
Java version: 1.8.0_412, vendor: Red Hat, Inc., runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.412.b08-1.el7_9.x86_64/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: linux, version: 3.10.0-1160.el7.x86_64, arch: amd64, family: unix2.2.2、Maven阿里云镜像
修改/usr/local/maven/conf/settings.xml
?xml version1.0 encodingUTF-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 athttp://www.apache.org/licenses/LICENSE-2.0Unless 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 theyre all using the same Maven| installation). Its 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 xmlnshttp://maven.apache.org/SETTINGS/1.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://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/repositorylocalRepository/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: trueinteractiveModetrue/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: falseofflinefalse/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.pluginGroupcom.your.plugins/pluginGroup--pluginGrouporg.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.|proxyidoptional/idactivetrue/activeprotocolhttp/protocolusernameproxyuser/usernamepasswordproxypass/passwordhostproxy.host.net/hostport80/portnonProxyHostslocal.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.|serveriddeploymentRepo/idusernamerepouser/usernamepasswordrepopwd/password/server--!-- Another sample, using keys to authenticate.serveridsiteServer/idprivateKey/path/to/private/key/privateKeypassphraseoptional; leave empty if not used./passphrase/server--serveridreleases/idusernameali/usernamepasswordali/password/serverserveridSnapshots/idusernameali/usernamepasswordali/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.|mirroridmirrorId/idmirrorOfrepositoryId/mirrorOfnameHuman Readable Name for this Mirror./nameurlhttp://my.repository.com/repo/path/url/mirror--mirror!--This sends everything else to /public --idnexus/idmirrorOf*/mirrorOf urlhttp://maven.aliyun.com/nexus/content/groups/public//url/mirrormirror!--This is used to direct the public snapshots repo in the profile below over to a different nexus group --idnexus-public-snapshots/idmirrorOfpublic-snapshots/mirrorOf urlhttp://maven.aliyun.com/nexus/content/repositories/snapshots//url/mirrormirror!--This is used to direct the public snapshots repo in the profile below over to a different nexus group --idnexus-public-snapshots1/idmirrorOfpublic-snapshots1/mirrorOf urlhttps://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 profileiddevelopment/idrepositoriesrepositoryidcentral/idurlhttp://central/urlreleasesenabledtrue/enabledupdatePolicyalways/updatePolicy/releasessnapshotsenabledtrue/enabledupdatePolicyalways/updatePolicy/snapshots/repository/repositoriespluginRepositoriespluginRepositoryidcentral/idurlhttp://central/urlreleasesenabledtrue/enabledupdatePolicyalways/updatePolicy/releasessnapshotsenabledtrue/enabledupdatePolicyalways/updatePolicy/snapshots/pluginRepository/pluginRepositories/profileprofile!--this profile will allow snapshots to be searched when activated--idpublic-snapshots/idrepositoriesrepositoryidpublic-snapshots/idurlhttp://public-snapshots/urlreleasesenabledfalse/enabled/releasessnapshotsenabledtrue/enabledupdatePolicyalways/updatePolicy/snapshots/repository/repositoriespluginRepositoriespluginRepositoryidpublic-snapshots/idurlhttp://public-snapshots/urlreleasesenabledfalse/enabled/releasessnapshotsenabledtrue/enabledupdatePolicyalways/updatePolicy/snapshots/pluginRepository/pluginRepositories/profile/profilesactiveProfilesactiveProfiledevelopment/activeProfileactiveProfilepublic-snapshots/activeProfile/activeProfiles!-- activeProfiles| List of profiles that are active for all builds.|activeProfilesactiveProfilealwaysActiveProfile/activeProfileactiveProfileanotherAlwaysActiveProfile/activeProfile/activeProfiles--
/settings2.3、安装Jenkins
2.3.1、安装 下载war包 下载地址https://get.jenkins.io/war-stable/ 这里我们选择2.346.1版本 运行 java -jar jenkins.war首次启动war包会在/root/.jenkins生成配置文件 待完全启动成功后 访问服务器8080端口完成配置 初始化后的密码 Jenkins initial setup is required. An admin user has been created and a password generated.
Please use the following password to proceed to installation:47cdd39226a34cafb684576a843159c0密码文件使用后会自动删除 访问http://192.168.119.135:8080/ 在游览器上展示页面如下就可以进行初始化了将 管理员账户密码 复制到对应的地方点击 继续 选择安装推荐的插件 这里建议点击 选择插件来安装在点击 无 不安装任何插件再点击 安装因为我们没有配置镜像安装插件是从外网下载过来的会比较慢并且下载的插件可能会出现不兼容等状况导致失败率很高 注意 我们发现安装推荐的插件失败因为我们没有配置镜像安装插件是从外网下载过来的会比较慢并且下载的插件可能会出现不兼容等状况导致失败率很高。我们先继续后面再配置镜像下载。参考文档https://blog.csdn.net/xhmico/article/details/136535498 进入到创建管理员页面填写账户信息后 保存并完成 usernamewtspasswordWts123456 进入以下页面配置 jenkins 的 url 一般使用默认的就行了保存并完成 初始化完成 可以点击 开始使用 Jenkins 直接登录进入 Jenkins
2.3.2、配置镜像地址
之前启动 Jenkins 时会打印出管理员账户密码所在文件例如/root/.jenkins/secrets/initialAdminPassword/root/.jenkins 就是 jenkins 的工作目录在 jenkins 的工作目录 .jenkins 中找到 hudson.model.UpdateCenter.xml 文件打开 将 https://updates.jenkins.io/update-center.json 替换成国内镜像网址并 保存
国内镜像网址https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json国外镜像网址https://mirror.xmission.com/jenkins/updates/update-center.json 再进入到 updates 目录下编辑 default.json 文件将该文件中国外的地址全部替换成国内的
https://www.google.com 全部替换成 https://www.baidu.com https://updates.jenkins.io/download 全部替换成 https://mirrors.tuna.tsinghua.edu.cn/jenkins
2.3.3、常用插件的安装
Jenkins 相当于一个平台它很多的功能都是通过对应的插件去实现的所以插件安装对于使用 Jenkins 非常的重要
在 Jenkins 中常用的插件如下
FoldersOWASP Markup FormatterBuild TimeoutCredentials BindingTimestamperWorkspace CleanupAntGradlePipelineGitHub Branch SourcePipeline:GitHub Groovy LibrariesPipeline:Stage ViewGitSSH Build AgentsMatrix Authorization StrategyPAM AuthenticationLDAPEmail ExtensionMailerDark ThemeLocalization: Chinese (Simplified)Maven Integration
下面我以安装插件 Locale 为例演示安装插件的大概步骤
访问 Jenkins 选择 Manage Jenkins 选择 Manage Plugins 选择 Available 搜索栏中搜索 Locale
如果下载页面没有红色的警告点击 Download now and install after restart 就会下载最新版本的插件安装并重启。
如果有类似Warning: This plugin is built for Jenkins 2.426.2 or newer. Jenkins will refuse to load this plugin if installed. 这样的提示就表明当前插件的版本和你所下载的 Jenkins 的版本不兼容很大概率会安装不成功这个时候就需要去下载兼容该 Jenkins 版本的插件
点击插件的名称打开该插件对应的网址 点击 Releases 再点击 checksums就可以看到插件对应的版本了 比如说我下载的 Jenkins 版本是 2.346.1那我下载 180.v207501dff9b_a_点击即可 插件下载完成 回到 Jenkins 中点击 Advanced 下拉找到 Deploy Plugin这里可以上传本地下载好的插件上传完之后点击 Deploy 就会开始安装该插件 可以在 Installed 中看到刚刚手动安装的插件了
搜索插件 Localization: Chinese
按照上述方式进行安装
安装好之后就重启 Jenkins 使该插件生效
重启方法在 URL 的后面加上 restart例如http://192.168.119.135:8080/restart 点击 Yes 即可重启 重启完成再次登录并选择 Manage Jenkins 选择 Configure System 找到 Locale 选项输入 zh_CN 勾选下面的选项点击 Apply 和 save 重启之后可以看到汉化完成 3、Jenkins Git Maven 自动化部署配置
3.1、新建Item 3.1.1、Git配置
git安装 在Jenkins环境服务下安装gityum install gitgit配置
3.1.2、Maven配置 3.1.3、Pom.xml配置 3.1.4、构建
点击按钮就可以一键构建
我们可以看到构建成功并且jar包存到到.jenkins/workspace/first/demo-01/target 我们查看是否有jar包并且运行该jar包测试 3.2、publish over ssh 配置
3.2.1、安装插件
在 Manage Jenkins 菜单里 - System Configuration - Manage Plugins 安装插件 Publish Over SSH
3.2.2、添加一台目标服务器
Manage Jenkins - System Configuration - Configure System找到 Publish over SSH 位置点击 新增 填写服务器信息 点击高级输入目标服务器密码 点击测试显示success则代表服务配置成功最后点击保存即可。
3.2.3、配置
点击任务列的first 点击配置点击 Add post-build setp - Send files or execute commands over SSH 修改配置 注意我这里不知道是测试服务器TestServer的jdk环境变量配置的问题还是权限问题没法通过该方法直接运行java命令只能指定jdk路径运行jar包这里我的启动命令为 nohup /usr/java/jdk1.8.0_341/bin/java -jar /root/xxoo/demo*.jar nohup.out 21
1)、超时机制
输出命令时一定要注意不要让窗口卡住不然Jenkins会认为认为一直没完成
2)、shell的日志输出
nohup java -jar /root/xxoo/demo*.jar nohup.out 21 3)、数据流重定向
数据流重定向就是将某个命令执行后应该要出现在屏幕上的数据传输到其他地方
标准输入stdin代码为0使用或; 标准输出stdout代码为1使用或; 标准错误输出stderr代码为2使用2或2 覆盖写 追加写
3.3、运行前清理 先在测试服务器TestServer编写一个脚本x.shjenkins在运行前会调用该脚本进行清理jar包和进程 #!/bin/bash#删除历史数据
rm -rf xxooappname$1
#获取传入的参数
echo arg:$1#获取正在运行的jar包pid
pidps -ef | grep $1 | grep java -jar | awk {printf $2}echo $pid#如果pid为空提示一下否则执行kill命令
if [ -z $pid ];
#使用-z 做空值判断thenecho $appname not startedelsekill -9 $pidecho $appname stoping....checkps -ef | grep -w $pid | grep java
if [ -z $check ];thenecho $appname pid:$pid is stopelseecho $appname stop failedfifi修改x.sh的权限不然没法调用该脚本 chmod 777 ./x.shjenkins配置杀死之前运行的进程 修改代码内容提交到git上重新在构建部署查看结果 修改“com.wts.TestController”类代码如下 RestController
public class TestController {RequestMapping(/)public String test() {return hello wordwelcome;}
}构建部署之后访问http://192.168.119.128:8888
3.4、几种构建方式
快照依赖构建/Build whenever a SNAPSHOT dependency is built 当依赖的快照被构建时执行本job 触发远程构建 (例如,使用脚本) 远程调用本job的restapi时执行本job job依赖构建/Build after other projects are built 当依赖的job被构建时执行本job 定时构建/Build periodically 使用cron表达式定时构建本job 向GitHub提交代码时触发Jenkins自动构建/GitHub hook trigger for GITScm polling Github-WebHook出发时构建本job 定期检查代码变更/Poll SCM 使用cron表达式定时检查代码变更变更后构建本job
3.4.1、触发远程构建/gitlab上改动自动构建
注意工作中不建议使用
代码改动自动可以使用gitlab的webhook回调钩子调起Jenkins的启动任务接口 在构建触发器中配置接口和token 安装插件Build Authorization Token Root这个插件作用就是启用token之后可以免登录 postman调用urlhttp://192.168.119.135:8080/buildByToken/build?jobfirsttoken123123就可以触发构建部署 配置gitlab的webhook回调钩子 注意点击添加webhook我们发现报错并不是url填错了而是本地请求不允许 解决办法 重新配置webhook可以看的已创建 测试push一下代码 可以看到自动构建部署了 访问http://192.168.119.128:8888/
3.4.2、定时构建
Jenkins cron表达式
标准cron
https://crontab.guru
Jenkins cron不是标准的cron表达式
第一个 * 表示每个小时的第几分钟取值0~59H * * * *
H每小时执行一次第二个 * 表示小时取值0~23* 15 * * * 表示每天下午3点
* 1 * * * 表示每天凌晨1点第三个 * 表示一个月的第几天取值1~31
* 1 5 * * 表示每月5日凌晨1点第四个 * 表示第几月取值1~12
* 15 5 1 * 表示每年几月执行第五个 * 表示一周中的第几天取值0~7其中0和7代表的都是周日
“/”
表示每隔多长时间比如 */10 * * * * 表示 每隔10分钟
“H”
hash散列值以job名取值获取到以job名为入参的唯一值相同名称值也相同这个偏移量会和实际时间相加获得一个真实的运行时间
意义在于不同的项目在不同的时间运行即使配置的值是一样的比如 都是15 * * * * 表示每个小时的第15分钟开始执行任务那么会造成同一时间内在Jenkins中启动很多job换成H/15 * * * *,那么在首次启动任务时会有随机值参与进来有的会在17分钟启动 有的会在19分钟启动随后的启动时间也是这个值。这样就能错开相同cron值的任务执行了。
H的值也可以设置范围
H * * * *表示一小时内的任意时间
*/10 * * * *每10分钟
H/10 * * * *每10分钟,可能是7,17,27起始时间hash步长不变
45 3 * * 1-6 每个周一至周六凌晨3点45 执行1次
45 3-5 * * 1-6 每个周一至周六凌晨3点45 凌晨4点45凌晨5点45 各执行1次
H(40-48) 3-5 * * 1-6 在40~48之间取值 其他同上
45 3-5/2 * * 1-6 每个周一至周六凌晨3点45 凌晨5点45 各执行1次
45 0-6/2 * * 1-6 * * 1-6 0点开始每间隔2小时执行一次 0:45、2:45、4:45
3.4.3、源码变更构建
使用Poll SCM 方式与Build periodically一样
会主动定期检查代码托管服务器上是否有变化一旦发生变化执行job构建
3.5、自动化部署到docker容器中 3.5.1、docker外挂目录
1)、手动命令启动docker外挂目录下的jar包
docker run -d -p 8080:8080 --name demo-out -v /root/jarfile/demo-1-0.0.1-SNAPSHOT.jar:/app.jar openjdk:11 java -jar app.jar2)、jenkins修改publish over ssh 配置
我们修改publish over ssh 配置让jenkins构建部署的时候直接可以运行在docker容器里。
添加一台目标服务器运行前清理 构建完之后配置 点击保存配置就修改好了我们就可以正常使用了
3.5.2、打包到容器内
1)、手动命令启动docker容器内的jar包 准备一台测试服务器 docker环境 准备支持jdk的镜像 FROM openjdk:11
COPY . /usr/src/myapp
WORKDIR /usr/src/myapp
RUN javac Main.java
CMD [java, Main]把jar包打包到容器内 配置国内镜像 修改/etc/docker/daemon.json文件没有的话创建一个 写入 {registry-mirrors: [https://ustc-edu-cn.mirror.aliyuncs.com,http://hub-mirror.c.163.com,https://registry.aliyuncs.com]
}重启服务 systemctl daemon-reload
systemctl restart dockerdockerfile FROM openjdk:11
EXPOSE 8080WORKDIR /rootADD jarfile/demo*.jar /root/app.jar
ENTRYPOINT [java,-jar,/root/app.jar]打包镜像 docker build -t demo .运行容器 docker run -d --name demo -p 8080:8080 demo 2)、jenkins修改publish over ssh 配置 添加一台目标服务器 运行前配置 项目代码里添加一个dockerfile文件 构建后的配置 点击保存配置就修改好了我们就可以正常使用了
4、Jenkins集群/并发构建
集群化构建可以有效提升构建效率尤其是团队项目比较多或是子项目比较多的时候可以并发在多台机器上执行构建。
4.1、Jenkins集群搭建 首先搞3台服务器 服务器名ip准备条件Jenkins-Server192.168.119.135jdk1.8、maven、gitJenkins-02192.168.119.136jdk1.8、maven、gitJenkins-03192.168.119.137jdk1.8、maven、git 在主服务器配置其他节点 点击 ManageJenkins - Manage nodes and clouds 添加新节点 填写新节点信息 点击保存我们就可以看到jenkins-02节点已经创建成功状态为已同步。 jenkins-03节点添加如上操作。
4.2、流水线 pipeline
流水线既能作为任务的本身也能作为Jenkinsfile
使用流水线可以让我们的任务从ui手动操作转换为代码化像docker的dockerfile一样从shell命令到配置文件更适合大型项目可以让团队其他开发者同时参与进来同时也可以编辑开发Jenkins-web-ui不能完成的更复杂的构建逻辑作为开发者可读性也更好。
4.2.1、完整语法
5个必备的组成部分
pipeline整条流水线
agent指定执行器
stages所有阶段
stage某一阶段可有多个
steps阶段内的每一步可执行命令4.2.2、测试脚本
1)、基础框架
pipeline {agent anystages {stage(拉取代码) {steps {echo 拉取代码完成}}stage(执行构建) {steps {echo 执行构建完成}}}post {always {echo 完成}failure {echo 失败}}
}2)、阶段视图 Stage View
点击构建 我们可以看到阶段视图 3)、blue ocean可视化界面
全新的流水线控制ui可重复执行某阶段代码
插件中心搜索blue ocean安装即可
4)、post
流水线完成后可执行的任务
always 无论流水线或者阶段的完成状态。changed 只有当流水线或者阶段完成状态与之前不同时。failure 只有当流水线或者阶段状态为failure运行。success 只有当流水线或者阶段状态为success运行。unstable 只有当流水线或者阶段状态为unstable运行。例如测试失败。aborted 只有当流水线或者阶段状态为aborted 运行。例如手动取消。
5)、agent
可以指定执行节点
label 指定运行job的节点标签
any 不指定由Jenkins分配
pipeline {agent {node {label jenkins-02}}stages {stage(拉取代码) {steps {sh sleep 10echo 拉取代码完成}}stage(执行构建) {steps {echo 执行构建完成}}}post {always {echo 完成}failure {echo 失败}}
}
4.2.3、pipeline中执行自动化构建
git拉取代码的脚本生成 点击流水线语法 选择git 配置git的相关信息 点击 生成流水线脚本 可以看到生成的脚本代码 git branch: main, credentialsId: gitlab, url: http://192.168.119.134/root/java-project.gitpublish over ssh脚本生成
1.选择 sshPublisher: Send build artifacts over SSH
配置和原先publish over ssh 配置一样这里就不贴图了。
把所有的操作通过流水线语法生成最后完整的jenkinsfile脚本
pipeline {agent anytools {maven maven3}stages {stage(拉取代码) {steps {git branch: main, credentialsId: gitlab, url: http://192.168.119.134/root/java-project.gitecho 拉取成功}}stage(执行构建) {steps {// sh mvn --versionsh cd demo-1mvn clean packageecho 构建完成}}stage(clean test server){steps{sshPublisher(publishers: [sshPublisherDesc(configName: testserver, transfers: [sshTransfer(cleanRemote: false, excludes: , execCommand: rm -rf *docker stop demo
docker rm demo
docker rmi demo
, execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: [, ], remoteDirectory: , remoteDirectorySDF: false, removePrefix: , sourceFiles: /root)], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])}}stage(发送jar包到测试服务器) {steps {sshPublisher(publishers: [sshPublisherDesc(configName: testserver, transfers: [sshTransfer(cleanRemote: false, excludes: , execCommand: , execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: [, ], remoteDirectory: /jarfile, remoteDirectorySDF: false, removePrefix: demo-1/target, sourceFiles: **/demo*.jar), sshTransfer(cleanRemote: false, excludes: , execCommand: docker build -t demo .
docker run -d -p 8080:8080 --name demo demo, execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: [, ], remoteDirectory: /, remoteDirectorySDF: false, removePrefix: demo-1/docker, sourceFiles: demo-1/docker/dockerfile)], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])echo jar send over!}}}
}把流水线的代码粘贴到脚本里 1)、声明式流水线
好处
更像是在Jenkins web ui中的操作可读性比较高可以使用blue ocean自动生成支持语法检查
坏处
代码逻辑能力比脚本式弱不能完成特别复杂的任务
2)、脚本式流水线
好处
更少的代码和弱规范要求更灵活的自定义代码操作不受约束可以构建特别复杂的工作流和流水线
坏处
读写对编程要求比较高比声明式流水线代码更复杂