前言碎语
采用基于Kubernetes的容器化技术架构具备显著优势,例如支持服务的弹性伸缩与故障自动修复,同时也便于实施蓝绿部署及灰度发布策略。近年来容器化技术演进迅速,若关注服务网格(Service Mesh)领域,会发现如Istio等新兴技术必须依托于成熟的容器化环境才能落地实践。
浅谈docker
可将Docker类比为JVM,二者均为虚拟机形态;Docker镜像对应JAR包,镜像运行于Docker容器内,正如JAR包运行于JVM中。JAR包的构建由Maven的pom.xml定义,而Docker镜像则需通过Dockerfile来定义打包过程。在容器化之前,开发交付的最终产物通常为JAR包;容器化后,需交付包含JAR包及稳定可移植运行环境的Docker镜像。以下展示一个最基础的Docker镜像构建示例:

执行命令 `docker build -t kl/sales .` 即可构建出一个可运行的镜像。
浅谈k8s的部署脚本
其实k8s的脚本没什么可说的,本身k8s的概念非常之多,具体可参考官方的文档,下面贴出我们的部署文件
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: sales-app
namespace: #namespace
spec:
replicas: 2
minReadySeconds: 130 # 从容器启动到应用正常提供服务
strategy: # k8s更新策略
type: RollingUpdate #滚动更新
rollingUpdate:
maxSurge: 2 # 更新时允许最大激增的容器数,默认 replicas 的 1/4 向上取整
maxUnavailable: 1 # 更新时允许最大 unavailable 容器数,默认 replicas 的 1/4 向下取整
template:
metadata:
labels:
app: sales-app
spec:
imagePullSecrets: #镜像拉取秘钥
- name: xx-xx-xx
containers:
- name: sales
image: xxx-vpc.cn-xx.aliyuncs.com/keking/sales:#Tag
imagePullPolicy: Always
env:
- name: runShell
value: #runShell
ports:
- containerPort: 6002
name: web
protocol: TCP
resources:
limits:
cpu: 600m
memory: 4Gi
requests:
cpu: 300m
memory: 100Mi
livenessProbe: #检查是否存活
httpGet:
path: /health
port: 6002
initialDelaySeconds: 240 #首次检查在多少时间后
periodSeconds: 180 #检查周期
timeoutSeconds: 3 #超时时间
failureThreshold: 3 #失败的阈值,连续三次
readinessProbe: #检查是否成功启动
httpGet:
path: /health
port: 6002
initialDelaySeconds: 140 #首次检查在多少时间后
periodSeconds: 300 #检查周期
timeoutSeconds: 3 #超时时间
---
apiVersion: v1
kind: Service
metadata:
name: sales-app
namespace: #namespace
labels:
app: sales-app
spec:
selector:
app: sales-app
ports:
- name: web
port: 80
targetPort: 6002
nodePort: 31942
type: NodePort
最后聊聊jenkins pipeline
与常规Jenkins Pipeline定义类似,引入容器化后主要增加了两个关键步骤:一是在生成JAR包后,依据前述Dockerfile构建Docker镜像,这要求Jenkins主机具备Docker运行环境;二是将Kubernetes部署脚本发送至K8s集群,该步骤借助Jenkins Kubernetes插件完成,具体脚本逻辑见下文。
podTemplate(label: 'jnlp-slave', cloud: 'kubernetes', containers: [
containerTemplate(
name: 'jnlp',
image: 'xx-vpc.cn-xx.aliyuncs.com/keking/jenkins-slave:latest',
alwaysPullImage: true
),
],
volumes: [
hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock'),
hostPathVolume(mountPath: '/usr/bin/docker', hostPath: '/usr/bin/docker'),
hostPathVolume(mountPath: '/usr/local/jdk', hostPath: '/usr/local/jdk'),
hostPathVolume(mountPath: '/usr/local/maven', hostPath: '/usr/local/maven'),
],
imagePullSecrets: ['registry-pull-secret'],
)
{
node("jnlp-slave") {
stage('Git Checkout') {
checkout([$class: 'GitSCM', branches: [[name: "*/${branch}"]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'xx', url: 'http://xx.xx.xx/xx/yudian-salesplatform-boot.git']]])
}
stage('Maven Build') {
script {
if ('true' == "${build}") {
sh "mvn clean install -U -P${profile} -Dmaven.test.skip=true"
} else {
echo "跳过maven build"
}
}
}
stage('Docker Build ') {
script {
if ('true' == "${build}") {
sh '''
docker login -u it_sh@keking-group -p x#xxx-vpc.cn-xx.aliyuncs.com
docker build -t xx-vpc.cn-xx.aliyuncs.com/keking/sales:${Tag} .
docker push xx-vpc.cn-xx.aliyuncs.com/keking/sales:${Tag}
'''
} else {
echo "跳过docker build"
}
}
}
stage('Deploy to K8s') {
script {
if('true' == "${deploy}"){
if ('prod' == "${profile}") {
sh '''
sed -i "s/#namespace/prod/g" deploy.yaml
sed -i "s%#runShell%java -Xmx2G -Xms2G -Xmn960M -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/dump.log -Xloggc:/tmp/gc.log -verbose:gc -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:MaxMetaspaceSize=128m -XX:MetaspaceSize=128m -jar -Ddev_meta=http://conf.x.ops:8801/ -Denv=DEV -Didc=prod app.jar%g" deploy.yaml
'''
}
if ('uat' == "${profile}") {
sh '''
sed -i "s/#namespace/uat/g" deploy.yaml
sed -i "s%#runShell%java -Xmx1536M -Xms1536M -Xmn960M -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/dump.log -Xloggc:/tmp/gc.log -verbose:gc -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:MaxMetaspaceSize=128m -XX:MetaspaceSize=128m -jar -Ddev_meta=http://conf.keking.ops:8801/ -Denv=DEV -Didc=sales_docker app.jar%g" deploy.yaml
'''
}
sh '''
sed -i "s/#Tag/${Tag}/g" deploy.yaml
'''
kubernetesDeploy configs: 'deploy.yaml', kubeConfig: [path: ''], kubeconfigId: '9c1da035-60b9-4bd8-aeae-1a31666280ce', secretName: '', ssh: [sshCredentialsId: '*', sshServer: ''], textCredentials: [certificateAuthorityData: '', clientCertificateData: '', clientKeyData: '', serverUrl: 'https://']
}else {
echo "跳过Deploy k8s"
}
}
}
}
}
综上所述,实现了从Jenkins到Kubernetes的完整CI/CD流程。当然,过程中涉及诸多细节未详尽展开,例如K8s集群本身的搭建(本文博主使用的是阿里云容器服务)。欢迎有同类容器化需求的同行共同交流探讨。
以上为Jenkins、Docker与K8s容器化之路脚本浅析的详细内容,更多关于相关技术的资料请关注本站其它相关文章!