DevOps Guide 2026

GitLab CI Optimization

เรียนรู้วิธี optimize GitLab CI/CD pipelines ด้วย caching, artifacts และ parallel jobs ลดเวลา run 40-60%

GitLab CI/CD Caching Parallel Jobs

Pipeline Flow / การทำงานของ Pipeline

Build compile & install Test unit & integration Deploy production Cache Storage node_modules, vendor, build Artifacts build output Parallel Jobs test:unit test:integration lint security:scan

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 เดียวกัน ลดเวลารอคอยผลลัพธ์ทั้งหมด

Sequential (Slow) Test Unit Test Integration Lint ~9 min total Parallel (Fast) Test Unit Test Integration Lint Security Scan ~3 min total Time 9 min vs 3 min
# Parallel jobs configuration
test:
  stage: test
  parallel: 4
  script:
    - npm test
  artifacts:
    reports:
      junit: results-$CI_NODE_INDEX.xml

FAQ / คำถามที่พบบ่อย

Q: Cache กับ Artifacts ต่างกันอย่างไร?
A: Cache เก็บ dependencies ไว้ใน runner เพื่อ reuse ใน builds ถัดไป Artifacts เป็น build output ที่ส่งระหว่าง stages หรือ download ได้
Q: parallel: 4 ใช้ทำอะไร?
A: รัน job เดียวกัน 4 instances พร้อมกัน ใช้ $CI_NODE_INDEX และ $CI_NODE_TOTAL เพื่อแบ่งงาน
Q: เวลา expire ของ artifacts?
A: GitLab default คือ 30 วัน ใช้ expire_in เพื่อกำหนดเวลา หรือใช้ global settings