Jenkins+Kubernetes+Docker完成微服务持续集成
新建 item
拉取代码,构建镜像
(1)创建NFS共享目录
让所有Jenkins-Slave构建指向NFS的Maven的共享仓库目录
vim /etc/exports
添加内容:
/opt/nfs/jenkins *(rw,no_root_squash)
/opt/nfs/maven *(rw,no_root_squash)
systemctl restart nfs #重启 NFS
(2)创建项目,编写构建 Pipeline
项目tensquare_back --> 配置 --> 参数化构建过程 --> Extended Choice Parameter
配置 harbor 凭证
红色修改部分:
1、gitlab上:项目 tensquare_back 的 HTTP地址
2、Jenkins上:gitlab的凭证
3、harbor的地址
4、harbor的凭证
5、harbor的地址
6、NFS安装的服务器(即 master的ip)
def git_address = "http://192.168.10.10:82/xxx_group/tensquare_back.git"
def git_auth = "fc0fab00-287d-4803-aba2-42ee7714028a"
//构建版本的名称
def tag = "latest"
//Harbor私服地址
def harbor_url = "192.168.10.60:85"
//Harbor的项目名称
def harbor_project_name = "tensquare"
//Harbor的凭证
def harbor_auth = "4a3d4e32-fc80-472c-8ca9-b942ceb6ac4a"
podTemplate(label: 'jenkins-slave', cloud: 'kubernetes', containers: [
containerTemplate(
name: 'jnlp',
image: "192.168.10.60:85/library/jenkins-slave-maven:latest"
),
containerTemplate(
name: 'docker',
image: "docker:stable",
ttyEnabled: true,
command: 'cat'
),
],
volumes: [
hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock'),
nfsVolume(mountPath: '/usr/local/apache-maven/repo', serverAddress: '192.168.10.90' , serverPath: '/opt/nfs/maven'),
],
)
{
node("jenkins-slave"){
// 第一步
stage('pull code'){
checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_address}"]]])
}
// 第二步
stage('make public sub project'){
//编译并安装公共工程
sh "mvn -f tensquare_common clean install"
}
// 第三步
stage('make image'){
//把选择的项目信息转为数组
def selectedProjects = "${project_name}".split(',')
for(int i=0;i<selectedProjects.size();i++){
//取出每个项目的名称和端口
def currentProject = selectedProjects[i];
//项目名称
def currentProjectName = currentProject.split('@')[0]
//项目启动端口
def currentProjectPort = currentProject.split('@')[1]
//定义镜像名称
def imageName = "${currentProjectName}:${tag}"
//编译,构建本地镜像
sh "mvn -f ${currentProjectName} clean package dockerfile:build"
container('docker') {
//给镜像打标签
sh "docker tag ${imageName} ${harbor_url}/${harbor_project_name}/${imageName}"
//登录Harbor,并上传镜像
withCredentials([usernamePassword(credentialsId: "${harbor_auth}", passwordVariable: 'password', usernameVariable: 'username')])
{
//登录
sh "docker login -u ${username} -p ${password} ${harbor_url}"
//上传镜像
sh "docker push ${harbor_url}/${harbor_project_name}/${imageName}"
}
//删除本地镜像
sh "docker rmi -f ${imageName}"
sh "docker rmi -f ${harbor_url}/${harbor_project_name}/${imageName}"
}
}
}
}
}
构建项目前,先创建仓库目录,再更改 NFS 共享目录权限
mkdir /opt/nfs/maven chmod -R 777 /opt/nfs/maven
Docker 命令执行权限(master、node1、node2 上操作)
chmod 777 /var/run/docker.sock
构建项目
构建成功
kubectl get pod --namespace kube-ops