2020-06-07 基于Docker构建企业Jenkins CI平台

1. CI/CD

持续集成(Continuous Integration,CI):代码合并、构建、部署、测试都在一起,不断地执行这个过程,并对结果反馈。
持续部署(ContinuousDeployment,CD):部署到测试环境、预生产环境、生产环境。
持续交付(ContinuousDelivery,CD):将最终产品发布到生产环境,给用户使用。

CI/CD流程
CI流程
CI流程

测试环境:
机器1:安装Jenkins和docker,IP:192.168.9.63
机器2:安装git和harbor,IP:192.168.9.64

2. 部署Jenkins和Docker

在机器1上操作,部署Jenkins:

[root@localhost ~]# ls    ---上传安装所需的包
anaconda-ks.cfg  apache-tomcat-8.0.46.tar.gz  jdk-8u45-linux-x64.tar.gz  jenkins.war
[root@localhost ~]# tar zxf jdk-8u45-linux-x64.tar.gz    ---解压jdk
[root@localhost ~]# tar zxf apache-tomcat-8.0.46.tar.gz    ---解压tomcat
[root@localhost ~]# mv jdk1.8.0_45 /usr/local/jdk    ---把jdk移动到/usr/local下
[root@localhost ~]# vi /etc/profile    ---添加以下两行
JAVA_HOME=/usr/local/jdk
PATH=$PATH:$JAVA_HOME/bin
[root@localhost ~]# source /etc/profile
[root@localhost ~]# java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
[root@localhost ~]# mv apache-tomcat-8.0.46 /usr/local/jenkins_tomcat
[root@localhost ~]# cd /usr/local/jenkins_tomcat/
[root@localhost jenkins_tomcat]# ls    ---tomcat的网站根目录为webapps
bin  conf  lib  LICENSE  logs  NOTICE  RELEASE-NOTES  RUNNING.txt  temp  webapps  work
[root@localhost jenkins_tomcat]# cd webapps/
[root@localhost webapps]# ls    ---默认的工程名是ROOT
docs  examples  host-manager  manager  ROOT
[root@localhost webapps]# rm -rf *    ---里面的东西用不到,删除掉
[root@localhost webapps]# ls
[root@localhost webapps]# mv /root/jenkins.war ./ROOT.war    ---这样就可以直接访问到Jenkins,不用加工程名
[root@localhost webapps]# ls
ROOT.war

[root@localhost webapps]# cd ../bin/
[root@localhost bin]# ./startup.sh 
Using CATALINA_BASE:   /usr/local/jenkins_tomcat
Using CATALINA_HOME:   /usr/local/jenkins_tomcat
Using CATALINA_TMPDIR: /usr/local/jenkins_tomcat/temp
Using JRE_HOME:        /usr/local/jdk
Using CLASSPATH:       /usr/local/jenkins_tomcat/bin/bootstrap.jar:/usr/local/jenkins_tomcat/bin/tomcat-juli.jar
Tomcat started.

[root@localhost ~]# vi /etc/docker/daemon.json    ---因为docker是在http上运行的,所以要配置可信任
{
        "registry-mirrors": ["http://f1361db2.m.daocloud.io"],
        "insecure-registries":["192.168.9.64"]    ---IP地址为仓库地址
}
[root@localhost ~]# systemctl restart docker

访问Jenkins,需要输入密码,密码在红框所在的文件下。

访问Jenkins
[root@localhost bin]# cat /root/.jenkins/secrets/initialAdminPassword    ---复制密码,登录
e41cfc8b278f437794a636cc80f6e38f

Jenkins显示离线,先跳过。

Jenkins显示离线,先跳过
输入帐号密码
下一步
安装成功
Jenkins主界面
创建项目
由于还没安装pipeline插件,所以没有相应按钮,返回首页
进入系统管理
进入插件管理
高级
拉到最下面,把https改成http,提交,检查
点击可用
输入pipeline查找
找到pipeline,安装
安装SCM
安装git

下一步,安装docker。

[root@localhost ~]# sudo yum install -y yum-utils \    ---安装依赖包
device-mapper-persistent-data \
lvm2
[root@localhost ~]# yum-config-manager \    ---安装yum源
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo
[root@localhost ~]# yum install docker-ce -y    ---安装docker
[root@localhost ~]# systemctl start docker
[root@localhost ~]# systemctl enable docker
[root@localhost ~]# curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://f1361db2.m.daocloud.io    ---配置后下载镜像会加快
[root@localhost ~]# systemctl restart docker

3. 部署代码仓库git和镜像仓库Harbor

使用机器2操作:
使用上面的方法安装docker,然后安装compose

[root@localhost ~]# curl -L https://github.com/docker/compose/releases/download/1.15.0/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
[root@localhost ~]# chmod +x /usr/local/bin/docker-compose

安装harbor

[root@localhost ~]# ls
anaconda-ks.cfg  harbor-offline-installer-v1.6.1.tgz
[root@localhost ~]# tar zxf harbor-offline-installer-v1.6.1.tgz
[root@localhost ~]# cd harbor
[root@localhost harbor]# ls
common                          docker-compose.yml    install.sh           prepare
docker-compose.chartmuseum.yml  ha                    LICENSE
docker-compose.clair.yml        harbor.cfg            NOTICE
docker-compose.notary.yml       harbor.v1.6.1.tar.gz  open_source_license
[root@localhost harbor]# vi harbor.cfg
hostname = 192.168.9.64    ---修改成当前机器IP
[root@localhost harbor]# ./prepare     ---执行准备工作
[root@localhost harbor]# ./install.sh    ---安装
[root@localhost harbor]# docker-compose ps    ---已启动
    Name              Command          Sta                      Ports                     
                                       te                                                 
-----------------------------------------------------------------------------------------
harbor-        /harbor/start.sh        Up                                                 
adminserver                                                                               
harbor-db      /entrypoint.sh          Up    5432/tcp                                     
               postgres                                                                   
harbor-        /harbor/start.sh        Up                                                 
jobservice                                                                                
harbor-log     /bin/sh -c              Up    127.0.0.1:1514->10514/tcp                    
               /usr/local/bin/ ...                                                        
harbor-ui      /harbor/start.sh        Up                                                 
nginx          nginx -g daemon off;    Up    0.0.0.0:443->443/tcp,                        
                                             0.0.0.0:4443->4443/tcp, 0.0.0.0:80->80/tcp   
redis          docker-entrypoint.sh    Up    6379/tcp                                     
               redis ...                                                                  
registry       /entrypoint.sh          Up    5000/tcp                                     
               /etc/regist ... 

访问Harbor,默认密码为Harbor12345。

访问Harbor

安装git

[root@localhost ~]# useradd git    ---创建git用户和密码
[root@localhost ~]# passwd git
Changing password for user git.
New password: 
Retype new password: 
passwd: all authentication tokens updated successfully.
[root@localhost ~]# yum install -y git    ---安装git
[root@localhost ~]# su - git    ---切换到git用户
[git@localhost ~]$ mkdir tomcat-java-demo.git    ---创建一个空目录
[git@localhost ~]$ cd tomcat-java-demo.git/
[git@localhost tomcat-java-demo.git]$ git --bare init    ---初始化为git仓库
Initialized empty Git repository in /home/git/tomcat-java-demo.git/
[git@localhost tomcat-java-demo.git]$ exit
logout
[root@localhost ~]# git clone https://github.com/lizhenliang/tomcat-java-demo    ---下载demo

把demo代码提交到git仓库:

[root@localhost ~]# cd tomcat-java-demo/
[root@localhost tomcat-java-demo]# ls
db  Dockerfile  LICENSE  pom.xml  README.md  src
[root@localhost tomcat-java-demo]# vi .git/config
[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
[remote "origin"]
        url = git@192.168.9.64:/home/git/tomcat-java-demo.git    ---把这里改成git私有仓库地址
        fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
        remote = origin
        merge = refs/heads/master

[root@localhost tomcat-java-demo]# git add .    ---添加本地文件到暂存区
[root@localhost tomcat-java-demo]# git commit -m 'all'    ---提交到本地
# On branch master
nothing to commit, working directory clean
[root@localhost tomcat-java-demo]# git push origin master    ---推送到远程仓库里
The authenticity of host '192.168.9.64 (192.168.9.64)' can't be established.
ECDSA key fingerprint is SHA256:9VmUJe/cRLjBYWdRBiCviJRhG/GwhKs/mKAqIeGydEg.
ECDSA key fingerprint is MD5:ae:93:94:50:3f:6d:63:cc:e8:42:25:92:f3:ef:3c:e9.
Are you sure you want to continue connecting (yes/no)? yes

在机器1上操作,把镜像推到Harbor仓库上:

[root@localhost ~]# docker pull lizhenliang/tomcat    ---拉取tomcat镜像
[root@localhost ~]# docker login 192.168.9.64    ---登录Harbor仓库
Username: admin
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store
Login Succeeded
[root@localhost ~]# docker tag lizhenliang/tomcat 192.168.9.64/library/tomcat:latest    ---推送前先打标签
[root@localhost ~]# docker push 192.168.9.64/library/tomcat:latest    ---推上去
推送成功

4. Jenkins配置Pipeline并构建Java项目测试

创建新项目
输入项目名称,选择流水线,确定
把事先写好的Pipeline脚本粘贴上去

Pipeline脚本:

node { 
   // 拉取代码
   stage('Git Checkout') { 
         checkout([$class: 'GitSCM', branches: [[name: '${branch}']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'a2db6b77-03d9-402a-8cbf-0307a638cb6c', url: 'git@192.168.9.64:/home/git/tomcat-java-demo.git']]])   }
   // 代码编译
   stage('Maven Build') {
        sh '''
        export JAVA_HOME=/usr/local/jdk
        /usr/local/maven/bin/mvn clean package -Dmaven.test.skip=true
        '''
   }
   // 项目打包到镜像并推送到镜像仓库
   stage('Build and Push Image') {
sh '''
REPOSITORY=192.168.9.64/library/tomcat-java-demo:${branch}
cat > Dockerfile << EOF
FROM 192.168.9.64/library/tomcat
MAINTAINER www.ctnrs.com
RUN rm -rf /usr/local/tomcat/webapps/*
ADD target/*.war /usr/local/tomcat/webapps/ROOT.war
EOF
docker build -t $REPOSITORY .
docker login 192.168.9.64 -u admin -p Harbor12345
docker push $REPOSITORY
'''
   }
   // 部署到Docker主机
   stage('Deploy to Docker') {
        sh '''
        REPOSITORY=192.168.9.64/library/tomcat-java-demo:${branch}
        docker rm -f tomcat-java-demo |true
        docker pull $REPOSITORY
        docker container run -d --name tomcat-java-demo -p 88:8080 $REPOSITORY
        '''
   }
}

由于Jenkins需要访问git仓库,所以需要配置通过密钥访问。

[root@localhost ~]# ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Ja5osJeknx1cCDoqBeyKWzCkK9RNBvqzUMKna381SwQ root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
|   .             |
|o . .E           |
|.* o.o. . .      |
|+.B.+. + o       |
|+==+..o S        |
|+*o*o+ *         |
|Bo+.= * o        |
|+o.+ + o         |
|.  .+ .          |
+----[SHA256]-----+
[root@localhost ~]# ls .ssh/
id_rsa  id_rsa.pub
[root@localhost ~]# ssh-copy-id git@192.168.9.64
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.9.64 (192.168.9.64)' can't be established.
ECDSA key fingerprint is SHA256:9VmUJe/cRLjBYWdRBiCviJRhG/GwhKs/mKAqIeGydEg.
ECDSA key fingerprint is MD5:ae:93:94:50:3f:6d:63:cc:e8:42:25:92:f3:ef:3c:e9.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
git@192.168.9.64's password: 
Number of key(s) added: 1
Now try logging into the machine, with:   "ssh 'git@192.168.9.64'"
and check to make sure that only the key(s) you wanted were added.

[root@localhost ~]# ls .ssh/
id_rsa  id_rsa.pub  known_hosts
[root@localhost ~]# cat .ssh/id_rsa    ---查看私钥
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAvyJhCSwNLqLo/mLb4pQoGtvConoHOoZUKZzjLbH50tDXLcVm
N4HTh52v1P7l8LmRXZFu94On61gNJ9R6Ev8T/56QC4VE9Jv+1crTbKPT3TPjHn9h
K+q4fWQO6rAkm8c0h65m0mMdh7dPALNn4vZGcIWVCf91zSDM5ZZPqvIzCRikI/z9
9B3nLh+djYIBCWkTPmvcz/9SKvcnwpw5OemYSkWjtb/k9o/iyv0pni8k7zPgq/+Y
SX7lWwzsgeMaGZqMgwF7UumHmSdWi5ZdmO8wClqy6s5x9gJ+o0proBX41H3dSV1H
aJ+QEhr2S+BPkv8NxSL6D1ECLL+jfG2WH//L9wIDAQABAoIBAQCrVOr86NMMOhZ3
ajDHI53rrZEESjTOnnk1MCBo5sAV3QT2T5v4J9VxHMXwPWnrZrzKzkJVd1v/19c7
G/ktrB/GJOHkodsVFfzSslThbt3MzOVLgk2dq3MjW50PfUP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nfJj0/9T4nWGwhU/dgYAIdPZHKYAbyxIJP8iDl7ZXQ==
-----END RSA PRIVATE KEY-----

新打开一个Jenkins页面

选择凭据
选择全局凭据
添加凭据
添加凭据
更新
复制ID
把ID粘贴到Pipeline指定位置

在机器1上操作,配置maven和git环境:

[root@localhost ~]# tar zxf apache-maven-3.5.0-bin.tar.gz
[root@localhost ~]# mv apache-maven-3.5.0 /usr/local/maven
[root@localhost ~]# git clone git@192.168.9.64:/home/git/tomcat-java-demo.git
自定义参数
自定义参数

保存退出。

构建
查看详情
查看控制台输出
控制台输出
构建成功
测试访问成功
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,732评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,496评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,264评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,807评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,806评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,675评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,029评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,683评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,704评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,666评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,773评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,413评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,016评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,204评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,083评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,503评论 2 343