Kubernetes Pipeline

Kubernetes 集群基于 Jenkins 的 CI/CD 流程实践

通过在 Kubernetes 集群上创建并配置 Jenkins Server 实现应用开发管理的 CI/CD 流程,并且利用 Kubernetes-Jenkins-Plugin 实现动态按需扩展 jenkins-slave。

安装 Kubernetes 集群

首先,需要有一个 Kubernetes 集群,本地可以运行 Minikube。

安装 Helm。

安装 Jenkins Server

helm install stable/jenkins --set rbac.install=true

详细的配置可以下载 https://github.com/kubernetes/charts.git 仓库查看并修改。

正常启动后可以看到如下提示,获取 Jenkins 地址和初始密码等。

k8s_pipeline_jenkins01

访问 Jenkins

查看服务

kubectl get svc

k8s_pipeline_jenkins02

浏览器打开 http://NodeIP:NodePort 即可访问。

测试

登录 Jenkins 后,新建一个流水线任务,将以下代码填入“Pipeline script”中,保存后运行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
podTemplate(label: 'golang-pod', containers: [
containerTemplate(
name: 'golang',
image: 'registry.cn-hangzhou.aliyuncs.com/spacexnice/golang:1.8.3-docker',
ttyEnabled: true,
command: 'cat'
),
containerTemplate(
name: 'jnlp',
image: 'registry.cn-hangzhou.aliyuncs.com/google-containers/jnlp-slave:alpine',
args: '${computer.jnlpmac} ${computer.name}',
command: ''
)
]
,volumes: [
/*persistentVolumeClaim(mountPath: '/home/jenkins', claimName: 'jenkins', readOnly: false),*/
hostPathVolume(hostPath: '/root/work/jenkins', mountPath: '/home/jenkins'),
hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock'),
hostPathVolume(hostPath: '/tmp/', mountPath: '/tmp/'),
])
{
node ('golang-pod') {
container('golang') {
git url: 'https://github.com/spacexnice/blog.git' , branch: 'code'
stage('Build blog project') {
sh("make")
}
}
}
}

同时在服务器上运行 watch kubectl get pods可以看到 Jenkins Server 通过 Kubernetes 启动了相应的 Pod 来执行任务。

k8s_pipeline_jenkins03

k8s_pipeline_jenkins04

k8s_pipeline_jenkins05

任务完成后,相应的 Pod 会被自动回收。