. 纭繚鎮ㄥ凡缁忔纭畨瑁呬簡 GitLab Runner锛屽苟鍦 GitLab 涓婂垱寤轰簡 CI/CD 閰嶇疆鏂囦欢銆傛偍鍙互鍒涘缓涓涓悕涓 .gitlab-ci.yml 鐨勬枃浠讹紝灏嗗叾鏀惧湪鎮ㄧ殑 GitLab 瀛樺偍搴撶殑鏍圭洰褰曚笅銆傚湪璇ユ枃浠朵腑锛屾偍闇瑕佸畾涔変竴涓垨澶氫釜闃舵锛屾瘡涓樁娈甸兘浼氭墽琛屼竴缁勪换鍔℃潵鏋勫缓銆佹祴璇曞拰閮ㄧ讲鎮ㄧ殑搴旂敤绋嬪簭銆備互涓嬫槸涓涓ず渚 .gitlab-ci.yml 閰嶇疆鏂囦欢锛
image: docker:19
services:
- name: docker:dind
command: ["--insecure-registry=registry.example.com:5000"]
stages:
- build
- test
- deploy
build:
stage: build
script:
- docker build -t registry.example.com:5000/my-app:$CI_COMMIT_SHA .
- docker push registry.example.com:5000/my-app:$CI_COMMIT_SHA
artifacts:
expire_in: 1 week
paths:
- Dockerfile
- src/
test:
stage: test
script:
- docker run --rm registry.example.com:5000/my-app:$CI_COMMIT_SHA ./vendor/bin/phpunit
deploy:
stage: deploy
script:
- helm upgrade --install --namespace my-namespace my-release charts/my-app
only:
- master
鍦ㄤ笂闈㈢殑绀轰緥涓紝Docker 鏋勫缓浜嗗簲鐢ㄧ▼搴忛暅鍍忥紝骞舵帹閫佸埌鍚嶄负 registry.example.com:5000 鐨 Docker Registry銆傝鏂囦欢杩樺寘鎷湪 Kubernetes 闆嗙兢涓婁娇鐢 Helm 閮ㄧ讲搴旂敤绋嬪簭鐨勫懡浠ゃ
浣跨敤 Helm 閮ㄧ讲搴旂敤绋嬪簭銆傛偍鍙互浣跨敤浠ヤ笅鍛戒护灏 Helm chart 閮ㄧ讲鍒 Kubernetes 闆嗙兢涓細
helm upgrade --install MY_RELEASE MY_CHART --namespace MY_NAMESPACE --set image.tag=MY_IMAGE_TAG
鍏朵腑锛孧Y_RELEASE 鏄偍瑕侀儴缃茬殑搴旂敤绋嬪簭鐨勫彂琛岀増鏈紝MY_CHART 鏄寘鍚簲鐢ㄧ▼搴 Kubernetes 璧勬簮鐨 Helm chart 鏂囦欢锛孧Y_NAMESPACE 鏄寚瀹氱殑 Kubernetes 鍛藉悕绌洪棿锛孧Y_IMAGE_TAG 鏄簲鐢ㄧ▼搴忕殑闀滃儚鏍囪銆
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-app-ingress
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "false"
spec:
rules:
- host: mydomain.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-app
port:
name: http
鍦ㄨ繖涓ず渚嬩腑锛孖ngress 璧勬簮灏嗗簲鐢ㄧ▼搴忓叕寮鍒 mydomain.com 鐨勬牴璺緞涓嬨傛偍鍙互鏍规嵁闇瑕佸湪 rules 閮ㄥ垎涓坊鍔犳洿澶氱殑涓绘満鍜岃矾寰勮鍒欙紝鎴栦娇鐢ㄥ叾浠 Ingress 鎺у埗鍣ㄧ殑娉ㄩ噴銆
apiVersion: v1
kind: Service
metadata:
name: my-app
spec:
type: ClusterIP
ports:
- name: http
port: 80
targetPort: 8080
鍦ㄨ繖涓ず渚嬩腑锛孲ervice 璧勬簮灏嗗簲鐢ㄧ▼搴忔毚闇插湪闆嗙兢鐨 IP 鍦板潃涓婄殑绔彛 80 涓娿 targetPort 瀛楁瀹氫箟浜嗗簲鐢ㄧ▼搴忓鍣ㄤ娇鐢ㄧ殑绔彛銆傚鏋滄偍鐨勫簲鐢ㄧ▼搴忓湪瀹瑰櫒涓娇鐢ㄧ殑绔彛涓嶅悓锛岃鏍规嵁闇瑕佷慨鏀规瀛楁銆
鏈鍚庯紝鎮ㄩ渶瑕佸垱寤轰竴涓厤鍚堟偍鐨 GitLab CI/CD 閰嶇疆鏂囦欢锛屽寘鍚儴缃 Helm chart 鍜 Kubernetes 璧勬簮鐨勫懡浠ゃ備互涓嬫槸涓涓ず渚嬶細
deploy:
stage: deploy
script:
- kubectl config use-context my-cluster
- kubectl create namespace my-namespace
- helm upgrade --install --namespace my-namespace my-release charts/my-app
- kubectl expose deployment my-app --namespace my-namespace --type=ClusterIP --port=80
- kubectl apply -f ingress.yaml --namespace my-namespace
鍦ㄨ繖涓ず渚嬩腑锛孋I/CD 閰嶇疆鏂囦欢鍖呮嫭浣跨敤 kubectl 鍛戒护鍒涘缓 Kubernetes 鍛藉悕绌洪棿銆佷娇鐢 Helm 閮ㄧ讲搴旂敤绋嬪簭銆佷互鍙婁娇鐢 kubectl 鍛戒护鍒涘缓 ClusterIP 绫诲瀷鐨 Service 鍜 Ingress 璧勬簮銆
浠ヤ笂灏辨槸鍙兘娑夊強鍒扮殑娴佺▼鍜屾楠わ紝鎮ㄥ彲浠ユ牴鎹偍鐨勫疄闄呮儏鍐佃繘琛岃皟鏁淬傚笇鏈涘鎮ㄦ湁鎵甯姪锛
鍙戣〃鍥炲