示例java文件:git@github.com:liaochao1991/tomcat-demo.git

1、准备测试文件:

git clone  https://github.com/liaochao1991/tomcat-demo.git

更改配置并且指定我们的仓库地址

git remote remove origin
git remote add origin git@192.168.25.135:/home/git/solo.git

推送到我们的仓库:

git add .
git commit -m "add all"
git push origin master

2、准备java镜像:

java:

[root@master env_dockerfile]# cat java_Dockerfile
FROM centos:7
ADD jdk-8u121-linux-x64.gz /usr/local
ENV JAVA_HOME /usr/local/jdk1.8.0_121
ENV PATH=${JAVA_HOME}/bin:$PATH

推送到harbo

docker login 192.168.25.135
docker build -t 192.168.25.135/library/java -f java_Dockerfile .
docker push 192.168.25.135/library/java

tomcat:

[root@master env_dockerfile]# cat tomcat-dockerfile
FROM 192.168.25.135/library/java
MAINTAINER liaochao

ADD apache-tomcat-8.5.23.tar.gz /tmp/

RUN mv /tmp/apache-tomcat-8.5.23 /usr/local/tomcat && \
    rm -rf apache-tomcat-8.5.23.tar.gz && \
    rm -rf /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

WORKDIR /usr/local/tomcat
EXPOSE 8080
CMD ["./bin/catalina.sh", "run"]

推送到harbo:

docker login 192.168.25.135
docker build -t 192.168.25.135/library/tomcat8.5 -f tomcat-dockerfile . .
docker push 192.168.25.135/library/tomcat8.5

3、准备认证信息

因为我们构建时在blog空间构建,所以我们需要在blog空间创建一个秘钥认证,用于拉取镜像:
创建空间:

kubectl create ns blog

docker login 登录仓库后会有认证信息存在本地中

cat /root/.docker/config.json | base64 -w 0

该命令会将你的认证信息通过base64编码,生成一个编码之后的字符串。
创建认证:

[root@k8s-g1 jenkins_yaml_file]# cat registry-pull-secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: registry-pull-secret
  #namespace: default
  namespace: blog
data:
  .dockerconfigjson: ewoJImF1dGhzIjogewoJCSIxMjcuMC4wLjE6NTAwMCI6IHsKCQkJImF1dGgiOiAiYkdsaGIyTm9ZVzg2TVRJek5EVTIiCgkJfSwKCQkiMTkyLjE2OC4xLjM5IjogewoJCQkiYXV0aCI6ICJiR2xoYjJOb1lXODZTbXhyYWlNeE1qTT0iCgkJfSwKCQkiMTkyLjE2OC4xLjQwOjUwMDAiOiB7CgkJCSJhdXRoIjogImJHbGhiMk5vWVc4Nk1USXpORFUyIgoJCX0KCX0sCgkiSHR0cEhlYWRlcnMiOiB7CgkJIlVzZXItQWdlbnQiOiAiRG9ja2VyLUNsaWVudC8xOC4wNi4wLWNlIChsaW51eCkiCgl9Cn0=
type: kubernetes.io/dockerconfigjson

认证相关信息

kubectl create -f registry-pull-secret.yaml
[root@master secret]# kubectl get secret -n blog
NAME                   TYPE                                  DATA   AGE
default-token-xz8xf    kubernetes.io/service-account-token   3      54m
registry-pull-secret   kubernetes.io/dockerconfigjson        1      12s

4、创建jenkins piplie模式

选择pipline模块构建:
在这里插入图片描述

选择丢弃旧的构建:
在这里插入图片描述
选择参数化构建:
git parameter构建:
其中的变量Tag可以传递给我们下面的jenkinsfile脚本文件
另外我们还需要一个选项参数用来回滚。
填写变量为deploy_env,
选项值为:deploy,rollback
在这里插入图片描述

流水线选择:
选择pipeline script from SCM
填写git 地址,选择账号密码,然后选择脚本路径:deploy/Jenkinsfile
在这里插入图片描述
我们所有的功能脚本在deploy文件下面,由Jenkinsfile调用。

5、准备pipline流水线配置文件:

我们在源码目录新建一个deploy文件,用于存放我们准备的的文件

[root@master solo]# ls
db  deploy  Dockerfile  LICENSE  pom.xml  README.md  src

准备Dockerfile用来打包我们的编译好的文件做成镜像。

[root@master solo]# cat Dockerfile
FROM 192.168.25.135/library/tomcat8.5
MAINTAINER liaochao
RUN rm -rf /usr/local/tomcat/webapps/*
ADD target/*.war /usr/local/tomcat/webapps/ROOT.war

我们完成cicd功能的文件全部都放置于deploy目录中

[root@master solo]# cd deploy/
[root@master deploy]# ls
deploy.yaml  Jenkinsfile

pipline流水线:
备注:这里使用了jeknins的slave节点192.168.25.136,也是基于本地搭建的模式,manven编译也是在本地编译,想要知道容器化的jenkins和salve的也可以咨询我。

[root@master deploy]# cat Jenkinsfile
node('192.168.25.136'){
      if ("${deploy_env}" == "rollback"){
          stage('start rollback'){
            sh '''
               /usr/local/bin/kubectl rollout undo deployment.apps/tomcat-java-demo -n blog --kubeconfig=/root/config
               '''
           }
          }
    else{
      stage('Git Checkout'){
         checkout([$class: 'GitSCM', branches: [[name: '${Tag}']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'fa30f76f-010e-4a9e-bbed-ead0f9a7d3a8', url: 'git@192.168.25.136:/home/git/solo.git']]])
      }
      stage('Unit Testing'){
      	echo "Unit Testing..."
      }
      stage('Maven Build'){
            sh '''export PATH=$PATH:/usr/local/jdk/bin
                 /usr/local/maven/bin/mvn clean package -Dmaven.test.skip=true
               '''
        }
      stage('Build and Push Image'){
          sh '''
          #echo "192.168.0.211 reg.aliangedu.com" >> /etc/hosts
          docker login -u liaochao -p Jlkj#123 192.168.25.135
	  #echo ${tag}
          #tag= ${mbranch}
          docker build -t 192.168.25.135/project/tomcat-java-demo:${Tag}  .
          docker push 192.168.25.135/project/tomcat-java-demo:${Tag}
          '''
      }
      stage('Deploy to K8S'){
         sh '''
         #tag=$(echo ${mbranch#*/})
         echo $(pwd)
         cd deploy
         sed -i "/demo/{s/latest/${Tag}/}" deploy.yaml
         ##sed -i "/namespace/{s/default/${Namespace}/}" deploy.yaml
         '''
          kubernetesDeploy configs: 'deploy/deploy.yaml', kubeConfig: [path: ''], kubeconfigId: '9181dba3-dab7-455c-a687-071274980bd0', secretName: '', ssh: [sshCredentialsId: '*', sshServer: ''], textCredentials: [certificateAuthorityData: '', clientCertificateData: '', clientKeyData: '', serverUrl: 'https://']
      }
      stage('Testing'){
          echo "Testing..."
      }
  }
}

用于编排的yaml文件:

[root@master deploy]# cat deploy.yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: tomcat-java-demo
  namespace: blog
spec:
  replicas: 1
  selector:
    matchLabels:
      project: www
      app: java-demo
  template:
    metadata:
      labels:
        project: www
        app: java-demo
    spec:
      imagePullSecrets:
      - name: registry-pull-secret
      containers:
      - name: tomcat
        image: 192.168.25.135/project/tomcat-java-demo:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 8080
          name: web
          protocol: TCP
        resources:
          requests:
            cpu: 0.5
            memory: 2Gi
          limits:
            cpu: 1
            memory: 2Gi
        livenessProbe:
          httpGet:
            path: /
            port: 8080
          initialDelaySeconds: 180
          timeoutSeconds: 30
        readinessProbe:
          httpGet:
            path: /
            port: 8080
          initialDelaySeconds: 200
          timeoutSeconds: 30

---
apiVersion: v1
kind: Service
metadata:
  name: tomcat-java-demo
  namespace: blog
spec:
  selector:
    project: www
    app: java-demo
  ports:
  - name: web
    port: 80
    targetPort: 8080
    nodePort: 30003
  type: NodePort

运行:
写完后,我们尝试运行一次jenkins,选则一次构建:
首先我们先提交代码:

git add -A
git commit -m "all"
git tag v5.5
git push origin master
git push origin v5.5

在这里插入图片描述
在这里插入图片描述
这里我采用的nodePort的方式暴露了项目端口,可以根据nodeIP+端口来访问项目
回滚:
我使用的原理是:
/usr/local/bin/kubectl rollout undo deployment.apps/tomcat-java-demo的这种方式,默认会回滚到上个版本,在jenkins直接选择rollback就可以实现回滚了,很实用。
,如果有gitlab 环境还可以加个钩子。代码有更新自动发布。

6 配置ingress

我们准备一个www.bes.com作为我们的访问域名,我们没有云解析商的域,就在自己本机上自定义解析,

[root@node2 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
#::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.25.137 www.liaochao.com
192.168.25.136 www.bes.com

自己pc上在C:\Windows\System32\drivers\etc 也加入对应的ip和解析域名。

编写ingress配置:

[root@master ingress]# cat tomcat_demo.yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  namespace: blog
  name: tomcat-example
  annotations:
    #配置重定向相关
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: www.bes.com
    http:
      paths:
      - path: /
        backend:
          #匹配需要代理的service名字
          serviceName: tomcat-java-demo
          #对应clusterip端口
          servicePort: 80

执行创建ingress服务:

kubectl apply -f tomcat_demo.yaml

检测:

[root@master ingress]# kubectl get ingress -n blog
NAME                   HOSTS              ADDRESS   PORTS   AGE
tomcat-example         www.bes.com                  80      4h12m
tomcat-nginx-example   www.liaochao.com             80      10m

访问:http://www.bes.com/
在这里插入图片描述

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐