k8s部署gin-vue-admin框架、gitlab-ci、jenkins pipeline 、CICD

news2024/12/28 5:58:17
测试环境使用的jenkins
正式环境使用的gitlab-ci

测试环境

  1. 创建yaml文件
apiVersion: v1
kind: ConfigMap
metadata:
  name: dtk-go-tiktok-admin-config
  labels:
    app.kubernetes.io/name: dtk-go-tiktok-admin
    app.kubernetes.io/business: infrastructure
    app.kubernetes.io/runtime: golang
    app.kubernetes.io/tier: backend
    app.kubernetes.io/environment: test
    app.kubernetes.io/managed-by: yong.xd
data:
  config.yaml: |
          max-age: 0
          show-line: true
          log-in-console: true

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: dtk-vue-tiktok-admin-config
  labels:
    app.kubernetes.io/name: dtk-go-tiktok-admin
    app.kubernetes.io/business: infrastructure
    app.kubernetes.io/runtime: golang
    app.kubernetes.io/tier: front
    app.kubernetes.io/environment: test
    app.kubernetes.io/managed-by: yong.xd
data:
  default.conf: |
    server{
      
        listen       80 default_server;
        server_name  _;
        access_log   /dev/stdout;
        error_log    /dev/stdout;
        root         /opt/app/dist/;
        location / {
                try_files $uri $uri/ /index.html;
            }
        location /api {
          proxy_set_header Host $http_host;
          proxy_set_header  X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          rewrite ^/api/(.*)$ /$1 break;  #重写
          add_header 'dtk-debug' 'api';
    #一个deployment2个pod是网络资源是共享的,所以可以直接代理
          proxy_pass http://127.0.0.1:8888; # 设置代理服务器的协议和地址
          }

       location /api/swagger/index.html {
         proxy_pass http://127.0.0.1:8888/swagger/index.html;
         }
        location /health {
          access_log off;
          return 200;
        }
    }
    
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: dtk-go-tiktok-admin
  labels:
    app.kubernetes.io/name: dtk-go-tiktok-admin
    app.kubernetes.io/business: infrastructure
    app.kubernetes.io/runtime: golang
    app.kubernetes.io/tier: backend
    app.kubernetes.io/environment: test
    app.kubernetes.io/managed-by: yong.xd
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: dtk-go-tiktok-admin
      app.kubernetes.io/business: infrastructure
      app.kubernetes.io/runtime: golang
      app.kubernetes.io/tier: backend
      app.kubernetes.io/environment: test
      app.kubernetes.io/managed-by: yong.xd
  template:
    metadata:
      labels:
        app.kubernetes.io/name: dtk-go-tiktok-admin
        app.kubernetes.io/business: infrastructure
        app.kubernetes.io/runtime: golang
        app.kubernetes.io/tier: backend
        app.kubernetes.io/environment: test
        app.kubernetes.io/managed-by: yong.xd
    spec:
      imagePullSecrets:
        - name: aliyun-regcred
      serviceAccountName: default
      securityContext:
      dnsPolicy: None
      dnsConfig:
        nameservers:
          - 172.31.74.196
        searches:
          - test1.svc.cluster.local
          - svc.cluster.local
          - cluster.local


      containers:
        - name: golang
          securityContext:
            runAsUser: 0
          image: "registry.buydance.com/dataoke-test/dtk-go-tiktok-admin-golang:latest"
          volumeMounts:
          - name: config
            mountPath: /opt/app/conf/
          ports:
            - name: http
              containerPort: 8888
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /health
              port: 8888
            initialDelaySeconds: 5
            periodSeconds: 20
            timeoutSeconds: 3
          readinessProbe:
            httpGet:
              path: /health
              port: 8888
            initialDelaySeconds: 5
            periodSeconds: 10
            timeoutSeconds: 3
          resources:
            requests:
              cpu: 1m
              memory: 20Mi

        - name: nginx
          securityContext:
          image: "registry.buydance.com/dataoke-test/dtk-go-tiktok-admin-nginx:latest"
          volumeMounts:
          - name: ng-config
            mountPath: /etc/nginx/conf.d/
          ports:
            - name: http
              containerPort: 80
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /health
              port: 80
            periodSeconds: 5
          readinessProbe:
            httpGet:
              path: /health
              port: 80
            periodSeconds: 5
          resources:
            requests:
              cpu: 1m
              memory: 64Mi
            limits:
              cpu: 200m
              memory: 256Mi
      volumes:
      - name: ng-config
        configMap:
          name: dtk-vue-tiktok-admin-config
      - name: config
        configMap:
          name: dtk-go-tiktok-admin-config
---
apiVersion: v1
kind: Service
metadata:
  name: dtk-go-tiktok-admin
spec:
  ports:
    - port: 80
      targetPort: 80
      protocol: TCP
      name: nginx
    - port: 8888
      targetPort: 8888
      protocol: TCP
      name: golang
  selector:
    app.kubernetes.io/name: dtk-go-tiktok-admin
    app.kubernetes.io/business: infrastructure
    app.kubernetes.io/runtime: golang
    app.kubernetes.io/tier: backend
    app.kubernetes.io/environment: test
    app.kubernetes.io/managed-by: yong.xd
  1. 启动服务
kubectl apply -f ./ -n test1
  1. 配置jenkins
#!/usr/bin/env groovy
import groovy.json.JsonOutput

String gitRepositryURL = 'https://test.com/dtk-go-tiktok-admin.git'
String dockerRegistry = 'test.com'
String dockerRegistryURL = 'https://test.com'
String dockerRegistryNameSpace = 'dataoke-test'
#dockerfile路径
String kubeManifestsRepo = '/home/jenkins/repo/dtk-kubernetes-test/app'
Map dockerFiles = ["nginx":"Dockerfile.test.nginx", "golang":"Dockerfile.test.golang"]
Map dockerImages = [:]
boolean notify = false

String jobBaseName = env.JOB_NAME[4..-1]
String jobK8sName = jobBaseName.replaceAll('_', "-") 

Map commitInfo = [:]
Map buildInfo = [:]

commitInfo.projectName = gitRepositryURL.replaceFirst(/^.*\/([^\/]+?).git$/, '$1') 
commitInfo.gitRepositryURL = gitRepositryURL
buildInfo.buildId = currentBuild.id

@NonCPS
def newSh(String cmd) {
	def script = '#!/bin/sh +x\n' << cmd
	result = sh(returnStdout: true, script: script.toString())
	return result
}

pipeline {
	agent any

	options {
		buildDiscarder logRotator(
			artifactDaysToKeepStr: '', 
			artifactNumToKeepStr: '', 
			daysToKeepStr: '10', 
			numToKeepStr: '10'
			)
	}

	parameters {
        
        choice( 
        	name: 'PENV',
        	choices: [
        		'dev1',
        		'dev2',
        		'test1',
        		'test2', 
        		'test3', 
        		'test4',
        		'test5',
                        'test6',
                        'test7',
        		'huise',
'huise4',
                        'huise3'
        	], 
        	description: '选择发布环境,默认发布至dev1测试环境'
        	)

        gitParameter(
        	name: 'GIT_BRANCH', 
            type: 'PT_BRANCH_TAG',
            branchFilter: 'origin/(.*)',
            defaultValue: 'master',
            selectedValue: 'DEFAULT',
            sortMode: 'DESCENDING_SMART',
            quickFilterEnabled: true, 
            description: 'Select your branch or tag.'
        	)
		 booleanParam(name: 'force', defaultValue: false, description: '代码重复强制发版')
    }

	stages {

		stage('预处理') {
			steps {
				script {
					def now = new Date()
					buildInfo.buildDate = now.format("yy-MM-dd HH:mm", TimeZone.getTimeZone('UTC'))

					def causes = currentBuild.getBuildCauses()
					buildInfo.buildUser = causes[0]['userName']
					userList = readYaml(file:'/etc/jenkins/users.yaml')
					if (!(PENV in userList.env.dev ) && !(buildInfo.buildUser in userList.user.allow)) {
						error(message: "开发只能发布环境到${userList.env.dev.join(',')}")			
					}
					buildInfo.gitBranch = GIT_BRANCH
					buildInfo.publishEnv = PENV
					currentBuild.description = "k8s环境: ${PENV} 构建人:${buildInfo.buildUser} 分支: ${GIT_BRANCH}"
					newSh("check.py -u ${buildInfo.buildUser} -e ${PENV}")
				}
			}
		}

		stage('同步代码仓库') {
			steps {
				script {
					def scmVars = checkout([
								$class: 'GitSCM', 
								branches: [[name: "${GIT_BRANCH}"]], 
								extensions: [[$class: 'CheckoutOption', timeout: 20], [$class: 'CloneOption', depth: 1]], 
								userRemoteConfigs: [[credentialsId: "5411496d-3606-4855-ab9c-2e4453cd2880", url: "${gitRepositryURL}"]]
								])
					commitInfo.gitCommit = scmVars.GIT_COMMIT
					commitInfo.gitBranch = GIT_BRANCH
					commitInfo.xiangmu_name = env.JOB_BASE_NAME
					commitInfo.commitDate = newSh('git log --pretty=format:"%ci" -1')
					commitInfo.cmmitMessage = newSh('git log --pretty=format:"%s" -1')

					String gitDiff = newSh('git diff HEAD^ HEAD')
					def committer = [:]
					committer.name = newSh('git log --pretty=format:"%cn" -1')
					committer.email =  newSh('git log --pretty=format:"%ce" -1')
					commitInfo.committer = committer
					
					String consoleStdout = "\n\n---------SYNCHRONIZE GIT REPOSITORY---------\nGit repo sync successfully.\n\n" + JsonOutput.prettyPrint(JsonOutput.toJson(commitInfo))
					println(consoleStdout)

					consoleStdout = "\n\n---------CHANGE LOGS---------\nGit diff:\n\n" + gitDiff
					println(consoleStdout)
					getDatabaseConnection(type: 'GLOBAL') {
						def sqlString="select commit_seccec from jenkins_commit.jenkins_jilu where xm_name = ? and env = ?"
                        def params=[commitInfo.xiangmu_name,PENV]
                        def rest_null = sql sql:sqlString,parameters:params
						if (rest_null.size() == 0){
						  def sqlString2="insert  into  jenkins_commit.jenkins_jilu(xm_name,env,commit_seccec)   values(?,?,?)"
                          def params2=[commitInfo.xiangmu_name,PENV,commitInfo.gitCommit]
						  sql sql:sqlString2,parameters:params2
						  println("mysql插入数据")
						}
						if (rest_null.size() >= 1) {
							   def Map rest = rest_null.get(0)
                        if (rest.get("commit_seccec") == commitInfo.gitCommit && force == "false"){
                        currentBuild.description = "k8s环境: ${PENV} 构建人:${buildInfo.buildUser} 分支: ${GIT_BRANCH} 构建失败: 代码重复不发版"
							   println("代码没有变化不做发版")
                               error "上一个版本和现在正在发的版本一致,不做发版"
							   }
						}
				
					}
				}
			}
		}

		stage('构建') {		
			agent {
          		docker { 
              		image 'registry.buydance.com/dataoke-test/golang:1.19'
              		args '--user root -v /data/jenkins_build_cache/.cache:/.cache'
              		args '--user root -v /data/lib/go:/go'
              		reuseNode true
          		}	
      		}

        	steps {
            	script {
					env.STAGE = "goujian"
            		def now = new Date()
					String buildDate = now.format("yy-MM-dd HH:mm", TimeZone.getTimeZone('UTC'))

         			sh (script: '#!/bin/sh +x\n' + '''
         			cd ./server
         			mkdir -p .cache
             		export GO111MODULE=on
             		export GOPROXY=https://goproxy.cn,direct
             		export GOPRIVATE="gitlab.buydance.com/*"
             		export CGO_ENABLED=0
             		go mod  tidy
             		go build -o main
         			'''
         			)

           			def files = findFiles(glob: '**/main')
           			String artifactPath = files[0].path
           			String sha1Checksum = sha1(file: artifactPath)
           			String sha256Checksum = sha256(file: artifactPath)
            				


            		consoleStdout = "\n\n---------BUILD RESULTS---------\nBuild info generated successfully.\n\n" + JsonOutput.prettyPrint(JsonOutput.toJson(buildInfo))
            		println(consoleStdout)
        		}	
			}
		}
		
		stage('构建vue') {		
			agent {
          		docker { 
              		image 'node:14.19.3-alpine3.15'
                    args '--user root -v /data/jenkins_build_cache/.cache:${HOME}/.cache'
                    args '--user root -v /data/lib/composer:/root/.composer'
                    reuseNode true
          		}	
      		}

        	steps {
            	script {
            		sh """
					cd ./web
                    npm config set puppeteer_download_host=https://npm.taobao.org/mirrors
                    npm i --registry=https://registry.npm.taobao.org
                    npm run build
                    """
					
            		consoleStdout = "\n\n---------BUILD RESULTS---------\nBuild info generated successfully.\n\n" + JsonOutput.prettyPrint(JsonOutput.toJson(buildInfo))
            		println(consoleStdout)
        		}	
			}
		}
		

		stage('Docker') {
			steps {
				script {
					env.STAGE = "DOCKERFIEL"
				//	docker.withRegistry(dockerRegistryURL, '8f1a40fa-3258-4717-825c-a9f87299916d') {
					docker.withRegistry(dockerRegistryURL) {
						
						String dockerFile = kubeManifestsRepo + '/' + jobBaseName + '/' + 'Dockerfile.test.nginx'
						    
						if (!fileExists(dockerFile)) {
							dockerFile = kubeManifestsRepo + '/' + jobK8sName + '/' + 'Dockerfile.test.nginx'
						}

						String dockerRepository = dockerRegistry + '/' + dockerRegistryNameSpace + '/' + jobK8sName + '-' + 'nginx'
						def customImage = docker.build(dockerRepository, "-f ${dockerFile} .")
						customImage.push(commitInfo.gitCommit)
						customImage.push('latest')
						
						dockerImages.nginx = dockerRepository + ':' + commitInfo.gitCommit

						dockerFile = kubeManifestsRepo + '/' + jobBaseName + '/' + 'Dockerfile.test.golang'
						    
						if (!fileExists(dockerFile)) {
							dockerFile = kubeManifestsRepo + '/' + jobK8sName + '/' + 'Dockerfile.test.golang'
						}

						dockerRepository = dockerRegistry + '/' + dockerRegistryNameSpace + '/' + jobK8sName + '-' + 'golang'
						customImage = docker.build(dockerRepository, "-f ${dockerFile} .")
						customImage.push(commitInfo.gitCommit)
						customImage.push('latest')

						dockerImages."golang" = dockerRepository + ':' + commitInfo.gitCommit
					}
				}
			}
		}

		stage('部署') {
			steps {
				script {
					env.STAGE = "bushu"
					dockerImages.each { k, v -> 
						newSh("kubectl -n ${PENV} set image deployment/${jobK8sName} ${k}=${v}")
						newSh("kubectl -n ${PENV} rollout status deployment/${jobK8sName} --timeout=2m")
					}
					String content = "![screenshot](https://comquent.de/wp-content/uploads/CQ-Pipeline-Kurs.png)\n\n### Jenkins Pipeline\n>**构建信息**:\n>- 构建项目: ${jobBaseName}\n>- 构建id: ${currentBuild.number}\n>- 构建人: ${buildInfo.buildUser}\n>- 构建分支: ${GIT_BRANCH}\n>- 发布环境: ${PENV}\n>**版本信息**:\n>- commit_hash: ${commitInfo.gitCommit}\n>- commit_date: ${commitInfo.commitDate}\n>- commit_message: ${commitInfo.cmmitMessage}\n>- committer: ${commitInfo.committer.name}"	
					def workflowMessage = [
						"msgtype": "actionCard",
						"actionCard":[
							"title":"构建信息",
							"text":content,
							"btnOrientation": "0",
							"btns": [
								[
									"title": "详细信息",
									"actionURL": "https://k8sjenkins.haojiequ.com/blue/organizations/jenkins/k8s_dtk_go_app_api/detail/k8s_dtk_go_app_api/${currentBuild.number}/pipeline"
								],
								[
									"title": "日志监控",
									"actionURL": "http://k8skibana.haou.com/app/kibana#/discover?_g=()&_a=(columns:!(_source),index:'18d51920-96c3-11eb-811f-1383c86a1d0',interval:auto,query:(language:kuery,query:''),sort:!(!('@timestamp',desc)))"
								],
							]
						]
					]	

					String workflowMessageJSON = JsonOutput.toJson(workflowMessage)
					timeout(unit: 'SECONDS', time: 30) {
						newSh("curl 'https://oapi.dingtalk.com/robot/send?access_token=9e91f6860736ff69e7f6f986179e154e497b70e26fd749c' -s -H 'Content-Type: application/json' -d '${workflowMessageJSON}'")
					}
				}
			}
		}
		stage("commit入库"){
             steps {
                  script{
                        getDatabaseConnection(type: 'GLOBAL') {
				        def sqlString3="update jenkins_commit.jenkins_jilu set commit_seccec=?    where xm_name=? and env=?;"
                        def params3=[commitInfo.gitCommit,commitInfo.xiangmu_name,PENV]
                        sql sql:sqlString3,parameters:params3
				  }
				  }
			 }
		}
	}
	post {
		failure {
			script{
			if (STAGE == "goujian") {
				println("----> goujian失败")
			}
		    if (STAGE == "bushu") {
			   println("----> bushu失败")		   
			}
			if (STAGE == "DOCKERFIEL") {
				println("----> DOCKERFIEL失败")
			}
	
			}
		}
	}
}
  1. 配置nginx
upstream  dtk-vue-tiktok-admin  {
        server dtk-go-tiktok-admin  weight=1 max_fails=0 fail_timeout=0s;
                keepalive 20;
}

server {
listen  80;
listen      443 ssl;
server_name test.com;
access_log  /var/log/nginx/dtest.com.access.log json;
error_log   /var/log/nginx/dtest.com.error.log;
ssl_certificate     conf.d/dtkcert/test.com.pem;
ssl_certificate_key conf.d/dtkcert/test.com.key;
more_set_headers 'Access-Control-Allow-Headers: Cookie,DNT,X-CSRF-Token,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,Auth-token';
more_set_headers 'Access-Control-Allow-Origin: *';
more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT';
more_set_headers 'Access-Control-Allow-Credentials: true';
default_type     'text/html';
set $backend 'dtk-vue-tiktok-admin';


include  public/deny.conf;
location / {
    proxy_pass http://$backend;
}

location ~ /\.ht {
    deny  all;
}
}
  1. jenkins机器上的dockerfile
[root@k8s-jenkins dtk-go-tiktok-admin]# cat Dockerfile.test.golang
FROM test.com/dataoke-test/alpine:3.12-CST as test
WORKDIR /opt/app
COPY  $CI_PROJECT_DIR/server/main /opt/app/main
CMD ["/opt/app/main", "-c", "/opt/app/conf/config.yaml"]

[root@k8s-jenkins dtk-go-tiktok-admin]# cat Dockerfile.test.nginx
FROM test.com/dataoke-test/openresty:base
WORKDIR /opt/app/dist/
COPY --chown=nobody:nobody web/dist /opt/app/dist

线上环境配置

  1. yaml其它都一样除了svc,因为svc需要绑定slb地址
apiVersion: v1
kind: Service
metadata:
  name: dtk-go-tiktok-admin
  annotations:
  #开启slb使用
    service.beta.kubernetes.io/alibaba-cloud-loadbalancer-force-override-listeners: "true"
   #slb地址
    service.beta.kubernetes.io/alibaba-cloud-loadbalancer-id: lb-2ze1hpcomc
    #    service.beta.kubernetes.io/alibaba-cloud-loadbalancer-protocol-port: "http:9090"
    service.beta.kubernetes.io/alibaba-cloud-loadbalancer-scheduler: "wrr"
    namespace: default
spec:
  type: LoadBalancer
  externalTrafficPolicy: Local
  ports:
    - port: 16107  #slb端口
      targetPort: 80 #pod服务端口
      protocol: TCP
  selector:
    app.kubernetes.io/name: dtk-go-tiktok-admin
    app.kubernetes.io/business: infrastructure
    app.kubernetes.io/runtime: golang
    app.kubernetes.io/tier: backend
    app.kubernetes.io/environment: prod
    app.kubernetes.io/managed-by: yong.xd
  1. 启动
cat .gitlab-ci.yml

stages:
  - build
  - package
  - docker
  - deploy
  - notify


build:
  stage: build
  image: test.com/dataoke-prod/golang:1.19-with-repo-cert
  cache:
    key:
      files:
      - go.mod
    paths:
      - .cache/pkg
  artifacts:
    expire_in: 20 mins
    untracked: false
    paths:
      - $CI_PROJECT_DIR/server/main
  script:
  - mkdir -p .cache
  - cd ./server 
  - export GOPATH="$CI_PROJECT_DIR/.cache"
  - go env -w GO111MODULE=on 
  - go env -w GOPROXY=https://goproxy.cn,direct 
  - go env -w GOPRIVATE=gitlab.buydance.com 
  - go env -w CGO_ENABLED=0
  - go build -o main
  only:
    - tags

package:
  stage: package
  image: test.com/dataoke-prod/node:14.19.3-alpine3.15
  script:
  - cd ./web
  - npm config set puppeteer_download_host=https://npm.taobao.org/mirrors
  - npm i --registry=https://registry.npm.taobao.org
  - npm run build
  cache:
    key:
      files:
      - package.json
    paths:
      - node_modules
  artifacts:
    name: "dist"
    untracked: false
    expire_in: 5 mins
    paths:
      - $CI_PROJECT_DIR/web/dist
  only:
    - tags



docker:
  stage: docker
  image: test.com/dataoke-prod/kaniko-executor:debug
  script:
  - mkdir -p /kaniko/.docker
  - echo "${DOCKER_AUTH_CONFIG}" > /kaniko/.docker/config.json
  - /kaniko/executor --context $CI_PROJECT_DIR --dockerfile $CI_PROJECT_DIR/Dockerfile.prod.nginx --destination test.aliyuncs.com/dataoke-prod/`echo ${CI_PROJECT_NAME} |sed 's@_@-@g'`-nginx:${CI_COMMIT_SHORT_SHA} --destination test.aliyuncs.com/dataoke-prod/`echo ${CI_PROJECT_NAME} |sed 's@_@-@g'`-nginx:latest
  - /kaniko/executor --context $CI_PROJECT_DIR --dockerfile $CI_PROJECT_DIR/Dockerfile.prod.golang --destination test.aliyuncs.com/dataoke-prod/`echo ${CI_PROJECT_NAME} |sed 's@_@-@g'`-golang:${CI_COMMIT_SHORT_SHA} --destination test.aliyuncs.com/dataoke-prod/`echo ${CI_PROJECT_NAME} |sed 's@_@-@g'`-golang:latest
  only:
    - tags

deploy:
  stage: deploy
  image: test.com/dataoke-prod/kubectl:1.18.1
  variables:
    GIT_STRATEGY: none
    K8S_NAME_SPACE: default
  script:
  - mkdir -p $HOME/.kube
  - echo "$KUBERNETES_SECRET" >> "$HOME/.kube/config"
  - kubectl version
  - kubectl get deployments.apps -n ${K8S_NAME_SPACE}
  - kubectl -n ${K8S_NAME_SPACE} set image deployment/`echo ${CI_PROJECT_NAME} |sed 's@_@-@g'` nginx=test.aliyuncs.com/dataoke-prod/`echo ${CI_PROJECT_NAME} |sed 's@_@-@g'`-nginx:${CI_COMMIT_SHORT_SHA} golang=test.aliyuncs.com/dataoke-prod/`echo ${CI_PROJECT_NAME} |sed 's@_@-@g'`-golang:${CI_COMMIT_SHORT_SHA} --record
  - kubectl rollout status deployment/`echo ${CI_PROJECT_NAME} |sed 's@_@-@g'`
  only:
    - tags


notifyFailWeChat:
  stage: notify
  image: test.aliyuncs.com/dataoke-prod/curl-image:v1
  script:
    - curl 'https://oapi.dingtalk.com/robot/send?access_token=6147ec1eb7d8b9bd5cd1b15f1c' -H 'Content-Type:application/json' -d "{\"msgtype\":\"text\",\"text\":{\"content\":\"$CI_PROJECT_NAME项目构建失败\n>本次构建由:$GITLAB_USER_NAME 触发\n>项目名称:$CI_PROJECT_NAME\n>提交号:$CI_COMMIT_SHA\n>提交日志:$CI_COMMIT_MESSAGE\n>构建分支:$CI_COMMIT_BRANCH\n>流水线地址:[$CI_PIPELINE_URL]($CI_PIPELINE_URL)\"}}"

  only:
    - tags
  when: on_failure

# 构建成功时的通知消息
notifySuccessWeChat:
  stage: notify
  image: test.aliyuncs.com/dataoke-prod/curl-image:v1
  script:
    - curl 'https://oapi.dingtalk.com/robot/send?access_token=d6147ec1eb7d8b9bd5cd1b15f1c' -H 'Content-Type:application/json' -d "{\"msgtype\":\"text\",\"text\":{\"content\":\"$CI_PROJECT_NAME项目构建成功\n>本次构建由:$GITLAB_USER_NAME 触发\n>项目名称:$CI_PROJECT_NAME\n>提交号:$CI_COMMIT_SHA\n>提交日志:$CI_COMMIT_MESSAGE\n>构建分支:$CI_COMMIT_BRANCH\n>流水线地址:[$CI_PIPELINE_URL]($CI_PIPELINE_URL)\"}}"
  only:
    - tags
  when: on_success
  1. 配置dockerfile
cat  Dockerfile.prod.golang

FROM test.aliyuncs.com/dataoke-prod/alpine:3.12-CST as prod
WORKDIR /opt/app
COPY  $CI_PROJECT_DIR/server/main /opt/app/main
CMD ["/opt/app/main", "-c", "/opt/app/conf/config.yaml"]

cat Dockerfile.prod.nginx

FROM test.aliyuncs.com/dataoke-prod/openresty:base
WORKDIR /opt/app/dist/
COPY --chown=nobody:nobody web/dist /opt/app/dist
  1. 配置nginx
upstream  dtk-go-tiktok-admin {
#svc内网ip
server 192.168.10.123:16107  weight=1 max_fails=0 fail_timeout=0s;
keepalive 20;
}

server {
listen  80;
listen      443 ssl;
server_name test.com;
access_log  /var/log/nginx/dtest.com.access.log json;
error_log   /var/log/nginx/dtest.com.error.log;
ssl_certificate     conf.d/dtkcert/test.com.pem;
ssl_certificate_key conf.d/dtkcert/test.com.key;

more_set_headers 'Access-Control-Allow-Headers: Cookie,DNT,X-CSRF-Token,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,Auth-token';
more_set_headers 'Access-Control-Allow-Origin: *';
more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT';
more_set_headers 'Access-Control-Allow-Credentials: true';
default_type     'text/html';
set $backend 'dtk-vue-tiktok-admin';

include  public/deny.conf;
location / {
proxy_pass http://$backend;
}

location ~ /\.ht {
deny  all;
}
}
  1. 结果图
    微信截图_20230928142620.png
    微信截图_20230928142639.png

微信截图_20230928142705.png
微信截图_20230928142657.png
微信截图_20230928142557.png
微信截图_20230928142535.png

原文

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1050995.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

提升您的Mac文件拖拽体验——Dropzone 4 for mac

大家都知道&#xff0c;在Mac上进行文件拖拽是一件非常方便的事情。然而&#xff0c;随着我们在工作和生活中越来越多地使用电脑&#xff0c;我们对于这个简单操作的需求也越来越高。为了让您的文件拖拽体验更加高效和便捷&#xff0c;今天我们向大家介绍一款强大的工具——Dro…

车载ADB环境搭建

ADB是什么 ADB&#xff0c;即 Android Debug Bridge 是一种允许模拟器或已连接的 Android 设备进行通信的命令行工具&#xff0c;它可为各种设备操作提供便利&#xff0c;如安装和调试应用&#xff0c;并提供对 Unix shell&#xff08;可用来在模拟器或连接的设备上运行各种命…

C语言中柔性数组的讲解与柔性数组的优势

前言:也许你从来没有听说过柔性数组&#xff08;flexible array&#xff09;这个概念&#xff0c;但是它确实是存在的。C99 中&#xff0c;结构中的最后一个元素允许是未知大小的数组&#xff0c;这就叫做"柔性数组"成员。 目录标题 柔性数组什么是柔性数组呢&#…

基于SSM的图书商城系统的设计与实现

基于SSM的图书商城系统的设计与实现 开发语言&#xff1a;Java数据库&#xff1a;MySQL技术&#xff1a;SpringSpringMVCMyBatisVue工具&#xff1a;IDEA/Ecilpse、Navicat、Maven 系统展示 图书列表 图书详情 个人中心 管理员界面 摘要 本文旨在探讨和展示一种基于Spring、…

PyTorch深度学习实战(18)——目标检测

PyTorch深度学习实战&#xff08;18&#xff09;——目标检测 0. 前言1. 目标检测1.1 基本概念1.2 目标检测应用1.3 模型训练流程 2. 创建自定义目标检测数据集2.1 安装图片标注工具2.2 数据集标注 3. 区域提议3.1 基本概念3.2 利用 SelectiveSearch 生成区域提议3.3 生成区域提…

VBA技术资料MF61:按每行指定字符数自动换行

【分享成果&#xff0c;随喜正能量】人生的旅途&#xff0c;一时的失意&#xff0c;一时的挫折&#xff0c;跌了一跤&#xff0c;不是人生的全部&#xff0c;只是人生的一个逗点&#xff0c;未来的成就、光辉&#xff0c;还有很多的虚线有待你继续去完成。。 我给VBA的定义&am…

JZ31 栈的压入、弹出序列

目录 一、题目 二、代码 一、题目 栈的压入、弹出序列_牛客题霸_牛客网 二、代码 class Solution { public:/*** 代码中的类名、方法名、参数名已经指定&#xff0c;请勿修改&#xff0c;直接返回方法规定的值即可** * param pushV int整型vector * param popV int整型vecto…

你真的知道MyBatisPlus吗?

你真的知道MyBatisPlus吗&#xff1f; 文章目录 你真的知道MyBatisPlus吗&#xff1f;快速入门入门案例常见注解常见配置 核心功能条件构造器AbstractWrapperUpdateWrapper条件构造器的用法 自定义SQLService接口 扩展功能代码生成静态工具逻辑删除枚举处理器JSON处理器 插件功…

【MATLAB-基于直方图优化的图像去雾技术】

【MATLAB-基于直方图优化的图像去雾技术】 1 直方图均衡2 程序实现3 局部直方图处理 1 直方图均衡 直方图是图像的一种统计表达形式。对于一幅灰度图像来说&#xff0c;其灰度统计直方图可以反映该图像中不同灰度级出现的统计情况。一般而言&#xff0c;图像的视觉效果和其直方…

【C++11】完美转发的使用以及万能引用

&#x1f30f;博客主页&#xff1a; 主页 &#x1f516;系列专栏&#xff1a; C ❤️感谢大家点赞&#x1f44d;收藏⭐评论✍️ &#x1f60d;期待与大家一起进步&#xff01; 文章目录 一、模板中的&& 万能引用右值引用变量的类型会被编译器识别为左值类型 二、完…

ModuleNotFoundError: No module named ‘taming‘

参考&#xff1a;https://stackoverflow.com/questions/69983020/modulenotfounderror-no-module-named-taming 【问题】 缺少taming模块&#xff0c;错误提示&#xff1a;ModuleNotFoundError: No module named ‘taming’ 【解决】 pip install taming-transformers 若发现安…

计算机毕设 基于时间序列的股票预测于分析

文章目录 1 简介2 时间序列的由来2.1 四种模型的名称&#xff1a; 3 数据预览4 理论公式4.1 协方差4.2 相关系数4.3 scikit-learn计算相关性 5 金融数据的时序分析5.1 数据概况5.2 序列变化情况计算 最后 1 简介 Hi&#xff0c;大家好&#xff0c;这里是丹成学长&#xff0c;今…

利用Pycharm将python文件打包为exe文件

前言 要将Python文件打包为可执行的EXE文件&#xff0c;您可以使用第三方工具&#xff0c;如PyInstaller、cx_Freeze或py2exe等。下面是使用PyInstaller来打包Python文件为EXE文件的步骤&#xff1a; 概述: PyInstaller 是一个用于将 Python 应用程序打包成可执行文件的工具…

大数据Flink(八十八):Interval Join(时间区间 Join)

文章目录 Interval Join&#xff08;时间区间 Join&#xff09; Interval Join&#xff08;时间区间 Join&#xff09; Interval Join 定义&#xff08;支持 Batch\Streaming&#xff09;&#xff1a;Interval Join 在离线的概念中是没有的。Interval Join 可以让一条流去 Jo…

kafka伪集群部署,使用docker环境拷贝模式

线上启动容器的方式是复制容器的运行环境出来&#xff0c;然后进行运行脚本的形式 1&#xff1a;在home/kafka目录下创建如下目录 2&#xff1a;复制kafka1容器内的数据/bitnami/kafka/data&#xff0c;直接放在1992_data里面&#xff0c;同理,复制kafka2容器内的数据/bitnami/…

GitHub配置SSH key

GitHub配置SSH key Git配置信息并生成密钥 设置用户名和密码 设置用户名 git config --global user.name "用户名" 设置邮箱 git confir --global user.email "邮箱" 生成密钥 ssh-keygen -t rsa -C "邮箱" 查看密钥 到密钥所保存的位置 复…

cgroup限制cpu使用率

写一段代码&#xff0c;如下所示&#xff0c;可以看到是单核拉满情况 #include <stdio.h> #include <pthread.h>int main() { int i 0; for(;;)i; return 0; }运行起来&#xff0c;通过top命令可以看到cpu使用率大致是100%&#xff0c;如下图所示&#xff1a; …

Python相关知识点

读取zip文件 import zipfilelistAipInfo zipfile.ZipFile(xxx.zip, r) print(listZipInfo.namelist()) # 以列表列出所有压缩文件列出所有被压缩的文件&#xff0c;以及文件名、文件大小和压缩结果大小。 for info in listZipInfo.infolist():print(info.filename, info.…

数据分析三剑客之一:Numpy详解及实战

1 NumPy介绍 NumPy 软件包是Python生态系统中数据分析、机器学习和科学计算的主力军。它极大地简化了向量和矩阵的操作处理。Python的一些主要软件包&#xff08;如 scikit-learn、SciPy、pandas 和 tensorflow&#xff09;都以 NumPy 作为其架构的基础部分。除了能对数值数据…

VMware下的ubuntu虚拟机,实现虚拟机与本地硬盘间的文件互传

本次安装vmware tools工具&#xff0c;以实现二者间的文件互传。 1、打开VMware软件&#xff0c;运行Ubuntu系统虚拟机 安装过程需在ubuntu虚拟机启动的情况下&#xff0c;才能进行安装&#xff1b; 2、安装VMware Tools 在VM主菜单栏中&#xff0c;点击 “虚拟机&#xff0…