Pipeline Flow / การทำงานของ Pipeline
Prerequisites / สิ่งที่ต้องเตรียม
- GitLab Project - ต้องมี GitLab project ที่เปิดใช้งาน CI/CD
- .gitlab-ci.yml - ความเข้าใจเกี่ยวกับ GitLab CI syntax
- GitLab Runner - ใช้ shared runner หรือ setup self-hosted runner
บทนำ (Introduction)
GitLab CI/CD มี built-in caching และ artifacts features ที่ช่วยลดเวลาทำงานของ pipeline โดยไม่ต้องดาวน์โหลด dependencies ซ้ำๆ และสามารถรันหลาย jobs แบบ parallel
เหตุผลที่อยาก optimize
การ optimize GitLab CI pipeline ช่วยลดเวลา run ลง 40-60% และลด load บน runner
GitLab CI Caching / ใช้ Caching ใน GitLab CI
GitLab CI มี built-in cache ที่เก็บ dependencies ไว้ใน runner และ reuse ใน builds ถัดไป
Example .gitlab-ci.yml:
image: node:20
# Define cache
cache:
key: $CI_COMMIT_REF_SLUG
paths:
- node_modules/
- .next/
stages:
- build
- test
- deploy
build:
stage: build
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 hour
test:
stage: test
dependencies:
- build
script:
- npm test
cache:
policy: pull-push
deploy:
stage: deploy
dependencies:
- build
script:
- npm run deploy:production
Cache Key
ใช้ $CI_COMMIT_REF_SLUG หรือ $CI_COMMIT_SHA เพื่อ unique key
Policy
pull-push (default), pull หรือ pull-push-push
Artifacts / เก็บ Build Output
Artifacts คือ files ที่สร้างจาก job และส่งต่อไปยัง jobs อื่นๆ หรือ download ได้
# Artifacts configuration
artifacts:
paths:
- dist/
- coverage/
expire_in: 1 week
when: on_success
reports:
junit: test-results.xml
coverage_report: coverage/index.html
Tip: ใช้ dependencies เพื่อรับ artifacts จาก job ก่อนหน้า ประหยัดเวลาดาวน์โหลด
Parallel Jobs / Jobs แบบ Parallel
Parallel jobs ทำงานพร้อมกันใน stage เดียวกัน ลดเวลารอคอยผลลัพธ์ทั้งหมด
# Parallel jobs configuration
test:
stage: test
parallel: 4
script:
- npm test
artifacts:
reports:
junit: results-$CI_NODE_INDEX.xml
FAQ / คำถามที่พบบ่อย
Q: Cache กับ Artifacts ต่างกันอย่างไร?
Q: parallel: 4 ใช้ทำอะไร?
$CI_NODE_INDEX และ $CI_NODE_TOTAL เพื่อแบ่งงาน
Q: เวลา expire ของ artifacts?
expire_in เพื่อกำหนดเวลา หรือใช้ global settings