基于 Jenkins+Docker+Git 的简单 CI 流程实践(下)
5.环境测试
5.1 远程 clone 代码测试
clone
云主机 docker-git
上的仓库 tomcat-java-demo.git
:
[root@docker-jenkins ~]# yum install git vim wget -y
[root@docker-jenkins ~]# git config --global user.email "hcc@c.com"
[root@docker-jenkins ~]# git config --global user.name "hcc"
[root@docker-jenkins ~]# git clone git@10.0.0.22:/home/git/tomcat-java-demo.git
Cloning into 'solo'...
The authenticity of host '10.0.0.22 (10.0.0.22)' can't be established.
ECDSA key fingerprint is SHA256:XNWQhGsAsqd84k/6OYV3xl1+mPGjtASsxeV1YVLZVas.
ECDSA key fingerprint is MD5:b4:bd:16:2b:de:e7:7c:fd:c5:dd:91:75:20:ff:3e:0a.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.22' (ECDSA) to the list of known hosts.
git@10.0.0.22's password:
warning: You appear to have cloned an empty repository.
[root@docker-jenkins ~]# ls
tomcat-java-demo
[root@docker-jenkins ~]# ls tomcat-java-demo/
doc Dockerfile LICENSE pom.xml README.md src
[root@docker-jenkins ~]#
5.2 拉取 Github demo 代码
模拟生产项目,拉取 Github 上的一个 demo,并上传至本地 git
库:
[root@docker-jenkins ~]# mv tomcat-java-demo tomcat-java-demo.bak
[root@docker-jenkins ~]# git clone https://github.com/dingkai163/tomcat-java-demo.git
Cloning into 'tomcat-java-demo'...
remote: Enumerating objects: 185, done.
remote: Counting objects: 100% (185/185), done.
remote: Compressing objects: 100% (165/165), done.
remote: Total 185 (delta 5), reused 178 (delta 4), pack-reused 0
Receiving objects: 100% (185/185), 4.50 MiB | 870.00 KiB/s, done.
Resolving deltas: 100% (5/5), done.
[root@docker-jenkins ~]# cd tomcat-java-demo
[root@docker-jenkins tomcat-java-demo]# vim .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
url = git@10.0.0.22:/home/git/tomcat-java-demo.git # 修改为本地的git库地址
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
[root@docker-jenkins tomcat-java-demo]# git add .
[root@docker-jenkins tomcat-java-demo]# git status
# On branch master
nothing to commit, working directory clean
[root@docker-jenkins tomcat-java-demo]# git commit -m "all"
# On branch master
nothing to commit, working directory clean
[root@docker-jenkins tomcat-java-demo]# git push origin master
git@10.0.0.22's password:
Counting objects: 229, done.
Compressing objects: 100% (185/185), done.
Writing objects: 100% (229/229), 4.52 MiB | 0 bytes/s, done.
Total 229 (delta 25), reused 229 (delta 25)
To git@10.0.0.22:/home/git/tomcat-java-demo.git
* [new branch] master -> master
[root@docker-jenkins tomcat-java-demo]#
5.3 自建镜像仓库上传下载
用云主机 buildimage
上传及下载镜像。
(1)修改主机名为:buildimage
[root@c-dfjgjesgqe ~]# hostnamectl set-hostname buildimage
[root@c-dfjgjesgqe ~]# hostname buildimage
Ctrl+D
退出后重新登陆生效。
(2)安装 DOCKER CE
安装所需包:
yum install -y yum-utils device-mapper-persistent-data lvm2 -y
设置稳定存储库:
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo -y
安装 DOCKER CE
(这一步比较慢,耐心等会儿!):
yum install docker-ce docker-ce-cli containerd.io -y
启动 Docker
:
systemctl start docker
首先在云主机 buildimage
上做本地 hosts
解析:
[root@buildimage ~]# echo "10.0.0.21 reg.marin.com" >> /etc/hosts
其次编辑 /etc/docker/daemon.json
文件,保存退出:
[root@buildimage ~]# vim /etc/docker/daemon.json
{"insecure-registries":["reg.marin.com"] }
最后重启下 docker
,让配置生效:
[root@buildimage ~]# systemctl restart docker
如果没有此步 docker login
将会报错:
[root@buildimage ~]# docker login reg.marin.com
Username (admin): admin
Password:
Error response from daemon: Get https://reg.marin.com/v1/users/: x509: certificate signed by unknown authority
此时可以通过 docker login reg.marin.com
登录 harbor
,输入用户名及密码:
[root@buildimage ~]# docker login reg.marin.com
Username (admin): admin
Password:
Login Succeeded
在 buildimage
云主机上构建 Tomcat 基础镜像,并推送到 harbor
镜像库:
[root@buildimage ~]# mkdir tomcat
[root@buildimage ~]# cd tomcat
[root@buildimage tomcat]# vim Dockerfile-tomcat
FROM centos:7
MAINTAINER hanchaochao www.jdcloud.com
ENV VERSION=8.5.39
RUN yum install java-1.8.0-openjdk wget curl unzip iproute net-tools -y && \
yum clean all && \
rm -rf /var/cache/yum/*
RUN wget http://mirrors.shu.edu.cn/apache/tomcat/tomcat-8/v${VERSION}/bin/apache-tomcat-${VERSION}.tar.gz && \
tar zxf apache-tomcat-${VERSION}.tar.gz && \
mv apache-tomcat-${VERSION} /usr/local/tomcat && \
rm -rf apache-tomcat-${VERSION}.tar.gz /usr/local/tomcat/webapps/* && \
mkdir /usr/local/tomcat/webapps/test && \
echo "ok" > /usr/local/tomcat/webapps/test/status.html && \
sed -i '1a JAVA_OPTS="-Djava.security.egd=file:/dev/./urandom"' /usr/local/tomcat/bin/catalina.sh && \
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
ENV PATH $PATH:/usr/local/tomcat/bin
EXPOSE 8080
CMD ["catalina.sh", "run"]
[root@harbor tomcat]# docker build -t tomcat:v1 -f Dockerfile-tomcat .
[root@harbor tomcat]# docker tag tomcat:v1 reg.marin.com/test/tomcat:v1
[root@docker-git-harbor tomcat]# docker login reg.marin.com
[root@docker-git-harbor tomcat]# docker push reg.marin.com/test/tomcat:v1
打开 harbor
的 test
仓库,查看镜像已经 push
成功。
6.CI 流程测试
6.1 Jenkins 安装必要插件
由于 Jenkins
是离线安装,所以在此需要配置一下插件下载地址:系统管理 → 插件管理 → Advanced(高级)。
修改下方地址,将 https
修改为 http
再点提交。
若出现问题无法获取插件,请尝试更换地址,如:https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/current/update-center.json
提交后点击可选插件,此时我们可以看到很多可获得插件。
首先搜索并安装 Pipeline
插件(如果搜索不到,在已安装中查看是否已经安装完毕)。
Pipeline
是一套运行于 Jenkins
上的工作流框架,将原本独立运行于单个或者多个节点的任务连接起来,实现单个任务难以完成的复杂流程编排与可视化。
再安装 SCM to job
插件,同上步骤(搜索,安装)。
6.2 Jenkins 项目创建
创建 Jobs。
选择【流水线】类型。
到这里我们就开始配置 Pipeline script
,点击【流水线语法】,来自动生成我们需要的配置。
如下图,我们选择 Git
方式,配置 Git
仓库地址,再添加认证相关。
在示例步骤中下拉选择如图选项,在 Repository URL
中填写 docker-git
上的 git
仓库地址,因为没有添加 jenkins
到 docker-git
容器的免密码登陆,所以截图中我们可以看到连接被拒绝的一大串红色提示,我们点击【添加】按钮。
这里我们使用的是秘钥认证方式,需要在容器 docker-jenkins
上生成密钥,然后将 jenkins
上生成的公钥发送到(docker-git
)git
服务器上,然后将 jenkins
上的生成的私钥内容粘贴到下图 Key
中,这样 jenkins
就可以免交互的拉取 git
仓库中的代码了。
[root@docker-jenkins ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
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:RQZ78bcVhLRQi8fWFPYmyvcnOqlxy980QwLsYFT/iz8 root@docker-jenkins
The key's randomart image is:
+---[RSA 2048]----+
| .o=oooo*.|
| .+.o=.* o|
| .oo+.Bo.+|
| .oo.+o.= |
| S .o.oo |
| .+..|
| . .o.++|
| +oo.E+|
| ..+o..o|
+----[SHA256]-----+
[root@docker-jenkins ~]# cd
[root@docker-jenkins ~]# ls .ssh/
id_rsa id_rsa.pub known_hosts
[root@docker-jenkins ~]# ssh-copy-id git@10.0.0.22
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/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@10.0.0.22's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'git@10.0.0.22'"
and check to make sure that only the key(s) you wanted were added.
[root@docker-jenkins ~]# cat .ssh/id_rsa
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAvrI8lBov+W8v+zSGdu2EP4BPP7Ml+T5KUwc2MKX1RNMMNQxc
tPUf7PjhbJJvuTpPPbS1+9PAlrPhikDrug3K4+sF/Fiy+/YgoVMlEFrXiSJK1xHi
ErDLA39WGq+E4ssth3JfrQHV+AINGAh1/NR+Uk+YmPDAuQgA1l7jSH1PN6qTdrYt
95HbklAA+Q3omAJJ4Uc80lk7ZdMcdCc0OAtHjCfbRv287qrH4U2OKSlOLljiBHBN
......
-----END RSA PRIVATE KEY-----
[root@docker-jenkins ~]#
配置完成后,我们就可以生成 Pipeline
脚本了。点击下方【生成流水线脚本】,然后复制方框内的内容。
将生成的流水线脚本复制出来,我生成的流水线脚本如下:
checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '9baf7156-9ac6-435d-b0db-86cae51c8fe6', url: 'git@10.0.0.22:/home/git/tomcat-java-demo.git']]])
将生成的流水线脚本记录完成后,我们点击左上角【返回】。
继续点击【配置】,完成流水线项目 tomcat-java-demo
的配置。
点击【流水线】,我们所需要的 Pipeline
脚本如下,将其粘贴到 script
的拉取代码模块中,并修改分支 */master
为 ${branch}
,其他模块内容自行编写,具体需要修改的地方和脚本如下:
node {
// 拉取代码
stage('Git Checkout') {
checkout([$class: 'GitSCM', branches: [[name: '${branch}']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '9baf7156-9ac6-435d-b0db-86cae51c8fe6', url: 'git@10.0.0.22:/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=reg.marin.com/test/tomcat-java-demo:${branch}
cat > Dockerfile << EOF
FROM reg.marin.com/test/tomcat:v1
MAINTAINER marin
RUN rm -rf /usr/local/tomcat/webapps/*
ADD target/*.war /usr/local/tomcat/webapps/ROOT.war
EOF
docker build -t $REPOSITORY .
docker login reg.marin.com -u admin -p 123456
docker push $REPOSITORY
'''
}
// 部署到Docker主机
stage('Deploy to Docker') {
sh '''
REPOSITORY=reg.marin.com/test/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
'''
}
}
在 Pipeline
脚本里面我们指定了一个 branch
参数,所以我们需要传递一个参数变量,这里我们选择参数化构建,默认值为 master
分支。
然后保存配置。
6.3 Jenkins 构建任务
构建前我们还需要做两个操作:
(1)添加 reg.marin.com
的 hosts
解析。
[root@docker-jenkins ~]# echo "10.0.0.21 reg.marin.com" >> /etc/hosts
(2)编辑 /etc/docker/daemon.json
文件,输入如下信息,保存退出。
[root@docker-jenkins ~]# vim /etc/docker/daemon.json
{"insecure-registries":["reg.marin.com"] }
最后重启下 docker
,让配置生效。
[root@docker-jenkins ~]# systemctl restart docker
返回到工作台,我们开始构建任务。
构建开始。
构建完成。
可以通过【Console Output
】输出查看 Jenkins
构建流程。
成功构建会提示:SUCCESS
。
通过浏览器来访问 tomcat-java-demo
项目:http://Jenkins主机公网IP:88/
。
可以看到正常访问,至此在京东云上基于 Jenkins+Docker+Git 的简单 CI 流程实践已经成功部署了。