ข้ามไปที่เนื้อหา

DevOps Project Example: จาก Code Push สู่ Production ด้วย GitOps, FluxCD และ Kubernetes

DevOps tutorial ส่วนใหญ่มีให้ดูแค่ diagram ของ pipeline โพสต์นี้ต่างออกไป เป็น pipeline ที่ใช้งานจริง กับ application จริง บน Kubernetes cluster จริง และอธิบายครบทุก tool ทุก workflow ว่าทำไมถึงออกแบบแบบนี้

เราจะไล่ดูระบบ CI/CD ทั้งหมดของ Slotmachine แอปแข่ง tournament แบบ multiplayer real-time เริ่มตั้งแต่ developer push code ขึ้น GitHub ผ่าน security และ quality gate 6 ด่าน จนไป deploy อัตโนมัติทั้งบน Nutanix on-premise cluster และ AWS EKS ทุกขั้นมีของจริงให้ดู ไม่มีตรงไหนที่ข้ามไปเฉย ๆ

Source code ทั้งหมดอยู่ใน 2 repository:


ภาพรวมทั้งหมด

ก่อนเจาะทีละส่วน ดู flow ทั้งหมดก่อน:

Developer
  │
  │ git push
  ▼
┌─────────────────────────────────────────────────────────────────┐
│  GitHub Actions — 6-Job CI Pipeline (slotmachine repo)          │
│                                                                 │
│  [1] CodeQL SAST → [2] Build+Test → [3] Locust Load Test       │
│  → [4] OWASP ZAP DAST → [5] Docker Build + Trivy Scan + Push  │
│  → [6] Update Deployment Repo (Kustomize image tag update)      │
└─────────────────────────────────────────────────────────────────┘
  │                         │
  │ push images              │ push to branch: development
  ▼                         ▼
Docker Hub              slotmachine-deployment repo
(pkhamdee/slotmachine)    ├── branch: development  ──► K8s DEV  (Nutanix)
  client:{sha}            ├── branch: qa           ──► K8s QA   (Nutanix)
  server:{sha}            └── branch: main         ──► K8s PROD (AWS EKS)
                               ▲              ▲
                          PR + DevOps    PR + QA Sign Off
                          Approval       + SDM Approval

All three clusters watched by FluxCD (CD Agent):
  FluxCD polls git branch → detects change → kustomize apply → K8s reconciled

NKP Management Cluster (Nutanix On-Premise):
  Manages DEV + QA clusters with SSO/IdP, Governance, Platform Services

มี 2 repository กับ 3 environment จาก commit ไปถึง production เป็นอัตโนมัติทั้งเส้น ส่วน human approval gate ก็วางไว้เฉพาะจุดที่ควรมีคนตัดสินใจ


Part 1: ปรัชญา — ทำไมต้องแยก Code กับ Deployment?

หัวใจของ architecture นี้เป็นเรื่องที่หลายทีมมองข้าม application code กับ deployment configuration แยกกันอยู่คนละ Git repository

ปัญหาของการเอามารวมกัน

ลองนึกภาพว่าเอาไฟล์ Kubernetes YAML ไปวางรวมกับ application code แบบนี้:

my-app/
├── src/          ← application code
├── tests/
└── k8s/          ← Kubernetes manifests  ← ⚠️ problematic
    ├── deployment.yaml
    └── service.yaml

สองอย่างนี้จะผูกกันแน่น แล้วตอน operate จริงจะเจ็บตัว:

  • แก้ CSS ไฟล์เดียวเป็น hotfix ก็ trigger deployment pipeline ทั้งเส้น
  • อยากรู้ว่า "ตอนนี้ production รันอะไรอยู่" ต้องไปไล่อ่าน commit history ของ application
  • Deploy พังแล้วจะ rollback ต้อง revert application code ด้วย ไม่ใช่แค่ config
  • Environment หลายตัว (dev/qa/prod) กระจายอยู่ตาม branch หรือ subdirectory รกไปหมด

ทางออกแบบ GitOps: 2 Repo, 2 หน้าที่

slotmachine/              ← Source of truth for the APPLICATION
  .github/workflows/ci.yml
  client/src/             ← React frontend
  server/src/             ← Node.js backend
  tests/locustfile.py

slotmachine-deployment/   ← Source of truth for WHAT RUNS IN THE CLUSTER
  base/                   ← Shared Kubernetes manifests
  overlays/development/   ← Dev environment configuration
  overlays/production/    ← Prod environment configuration

ดูโค้ด: slotmachine app repo · slotmachine-deployment repo

กฎมีข้อเดียว: application repo ห้ามมี Kubernetes manifest และ deployment repo ห้ามมี application source code สองฝั่งเชื่อมกันด้วย image tag อย่างเดียว คือ Git SHA สั้น ๆ ที่ CI pipeline เขียนลง deployment repo ให้เอง

นี่แหละโมเดล GitOps Git เป็น single source of truth ของ desired state ของ cluster CI runner ไม่ต้อง kubectl apply อะไรเลย cluster จะ pull desired state จาก Git เอง ไม่ต้องรอ pipeline push เข้ามา

ได้ประโยชน์ทันทีตั้งแต่วันแรก

ปัญหา ไม่แยก repo แยกแบบ GitOps
"prod รันอะไรอยู่?" ขุดหาใน CI log เปิด overlays/production/kustomization.yaml ดู
Rollback prod Revert app code แล้ว redeploy Revert PR ใน deployment repo
Audit trail ปนกับ commit แก้โค้ด Commit history มีแต่เรื่อง deployment ล้วน ๆ
Environment drift Copy-paste config ไปมา Kustomize base + overlay
Access control Dev แตะ prod infra ได้ Dev push ได้แค่ app repo ส่วน deployment repo เป็นของทีม infra

Part 2: Application — Slotmachine

ก่อนดู pipeline มาดูก่อนว่าของที่จะ deploy คืออะไร

Slotmachine เป็นแอปแข่ง slot แบบ multiplayer real-time ผู้เล่นแข่งกันในแต่ละ session ที่มีเวลาจำกัด ใครหมุนวงล้อแล้วได้ balance สูงสุดชนะ scoreboard อัปเดตสดทุกวินาที และมี admin เป็นคนคุมจังหวะของ session

Tech Stack

Frontend:  React 18 + Vite (SPA) served by Nginx
Backend:   Node.js + Express + Socket.io
Database:  MongoDB 7 + Mongoose
Cache:     Redis 7 (Socket.io multi-pod fan-out via ioredis pub/sub)
Container: Docker (client image: nginx:alpine, server image: node:20-alpine)

Architecture ภายใน Kubernetes

Internet
  │
  ▼
AWS NLB (Production) / LoadBalancer Service (Dev/QA)
  │
  ▼
┌─────────────────────────────────────────────┐
│  client Pod × 4 (prod) / × 1 (dev)         │
│  nginx:alpine                               │
│  ├── serves /  → React SPA (static files)  │
│  ├── proxies /api/*  → server:3001         │
│  └── proxies /socket.io/* → server:3001    │
└─────────────────────────────────────────────┘
  │
  ▼
┌─────────────────────────────────────────────┐
│  server Pod × 6 (prod) / × 1 (dev)         │
│  node:20-alpine                             │
│  ├── Express REST API (port 3001)           │
│  ├── Socket.io server (real-time events)    │
│  └── Mongoose (MongoDB) + ioredis (Redis)  │
└─────────────────────────────────────────────┘
  │               │
  ▼               ▼
MongoDB         Redis
StatefulSet     Deployment
(20Gi PVC prod) (pub/sub adapter)

พอ server มีหลาย pod ก็ต้องใช้ Redis เป็น Socket.io adapter เวลา server pod ตัวหนึ่ง broadcast scoreboard ใหม่ Redis จะ fan-out event ไปให้ server pod ตัวอื่นทุกตัว แล้วแต่ละตัวก็ส่งต่อให้ client ที่ต่ออยู่กับตัวเอง ถ้าไม่มี Redis client ที่ต่อคนละ pod จะเห็น scoreboard ไม่ตรงกัน

โครงสร้าง Repository

slotmachine/
├── .github/workflows/ci.yml      ← 6-job CI pipeline
├── .zap/rules.tsv                ← OWASP ZAP alert filter rules
├── docker-compose.yml            ← Local development stack
├── tests/locustfile.py           ← Load test scenarios
├── client/
│   ├── Dockerfile
│   ├── nginx.conf                ← SPA routing + API proxy config
│   ├── vite.config.js
│   └── src/
│       ├── components/           ← 12 React components
│       ├── hooks/                ← useGame, useSession
│       ├── api/gameApi.js
│       └── __tests__/            ← 97 Vitest tests
└── server/
    ├── Dockerfile
    └── src/
        ├── config/gameConfig.js
        ├── controllers/
        ├── middleware/adminAuth.js
        ├── models/               ← 5 MongoDB schemas
        ├── routes/
        └── services/
            ├── SessionManager.js ← State machine + timers
            └── slotEngine.js     ← Spin logic + payout table

Part 3: CI Pipeline — 6 Job ไล่ดูทีละ Gate

CI pipeline อยู่ใน .github/workflows/ci.yml ทุก push และทุก pull request รันครบ 6 job ยกเว้น 2 job สุดท้าย (container push กับ GitOps update) ที่รันเฉพาะบน branch main

push / PR
  │
  ├─── [1] code-scan         (CodeQL SAST)
  ├─── [2] build-and-test    (npm + Vitest + node:test)
  ├─── [3] performance-test  (Locust load test)
  ├─── [4] dast-zap          (OWASP ZAP DAST)
  │
  └── all 4 pass?
        │
        ├─── [5] container-build-scan-push  (Docker + Trivy + DockerHub)
        └─── [6] update-gitops              (Kustomize image tag → deployment repo)
                  (main branch only for jobs 5 and 6)

Job 1: CodeQL SAST — เจอช่องโหว่ก่อน Ship

SAST (Static Application Security Testing) วิเคราะห์ source code ตรง ๆ ไม่ต้องรันโปรแกรม

# .github/workflows/ci.yml (simplified)
code-scan:
  runs-on: ubuntu-latest
  permissions:
    security-events: write
  steps:
    - uses: actions/checkout@v4
    - uses: github/codeql-action/init@v3
      with:
        languages: javascript
        queries: security-extended   # Includes OWASP Top 10 patterns
    - uses: github/codeql-action/autobuild@v3
    - uses: github/codeql-action/analyze@v3

CodeQL สร้าง semantic model ของโค้ดขึ้นมา เลยตาม data flow ได้จริง ไม่ได้แค่จับ pattern ของข้อความ สิ่งที่เจอได้มีเช่น: - SQL/NoSQL injection ตรงที่ user input ไหลไปถึง query - XSS ตรงที่ข้อมูลที่เชื่อไม่ได้ไปโผล่ใน DOM - Prototype pollution ใน JavaScript - ช่องโหว่ path traversal

ผลขึ้นใน GitHub Security tab เลย ถ้าเจอระดับ Critical ก็ merge PR ไม่ได้

Job 2: Build and Test — 118 Test ไม่มีหยวน

build-and-test:
  runs-on: ubuntu-latest
  services:
    mongodb:
      image: mongo:7
      ports: ['27017:27017']
    redis:
      image: redis:7-alpine
      ports: ['6379:6379']
  steps:
    - uses: actions/checkout@v4
    - uses: actions/setup-node@v4
      with: { node-version: '20' }
    - run: npm ci
    - run: npm run test --workspace=client   # 97 Vitest tests
    - run: npm run test --workspace=server   # 21 node:test tests
    - run: npm run build --workspace=client  # Vite production build

ทั้ง 118 test รันกับ MongoDB และ Redis ตัวจริง ไม่มี mock หรือ stub ที่ database layer เลย และ build artifact ต้องสร้างเสร็จและผ่านการ verify ก่อน ถึงจะเริ่ม build container

Job 3: Performance Test — จับ Regression ก่อน User เจอ

performance-test:
  runs-on: ubuntu-latest
  services:
    mongodb: { image: mongo:7 }
    redis:   { image: redis:7-alpine }
  steps:
    - run: pip install locust
    - run: |
        node server/server.js &
        sleep 5
        locust -f tests/locustfile.py \
          --headless -u 2 -r 1 -t 10s \
          --host http://localhost:3001

locustfile.py เล่นแบบที่ user จริงเล่น คือสร้าง session หมุนวงล้อ แล้วเช็ค scoreboard พอรันทุก PR ก็จับ performance regression ได้ตั้งแต่ยังไม่ขึ้น environment ไหน เช่น database query ที่ช้าลง หรือโค้ดที่ไป block event loop

Job 4: DAST — ลองโจมตี Application ที่รันอยู่

DAST (Dynamic Application Security Testing) ยิงเข้า application ที่รันอยู่จากข้างนอก เหมือนที่ attacker ตัวจริงทำ งานนี้ใช้ OWASP ZAP ซึ่งเป็น open-source tool ที่วงการใช้เป็นมาตรฐาน

dast-zap:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v4
    - name: Start application stack
      run: docker compose up -d && sleep 15

    # On PRs: baseline scan (passive, fast, ~2 min)
    - name: ZAP Baseline Scan
      if: github.event_name == 'pull_request'
      uses: zaproxy/action-baseline@v0.13.0
      with:
        target: 'http://localhost:8080'
        rules_file_name: '.zap/rules.tsv'

    # On main push: full active scan (active attacks, ~15 min)
    - name: ZAP Full Scan
      if: github.ref == 'refs/heads/main'
      uses: zaproxy/action-full-scan@v0.11.0
      with:
        target: 'http://localhost:8080'
        rules_file_name: '.zap/rules.tsv'

สิ่งที่ ZAP ลองยิง: - SQL/NoSQL injection (ส่ง payload แนว ' OR 1=1 --) - XSS (ยัด <script>alert(1)</script> ใส่ทุก form field) - CSRF, clickjacking และ security header ที่ลืมใส่ - ลอง bypass authentication

ส่วนไฟล์ .zap/rules.tsv ไว้ปิด false positive ที่รู้อยู่แล้ว ผลที่เหลือจะได้มีแต่เรื่องที่ต้องดูจริง

Job 5: Container Build, Scan และ Push

container-build-scan-push:
  needs: [code-scan, build-and-test, performance-test, dast-zap]
  runs-on: ubuntu-latest
  steps:
    - name: Build client image
      run: |
        docker build -t pkhamdee/slotmachine:client-${{ github.sha }} \
                     -t pkhamdee/slotmachine:client \
                     ./client

    - name: Build server image
      run: |
        docker build -t pkhamdee/slotmachine:server-${{ github.sha }} \
                     -t pkhamdee/slotmachine:server \
                     ./server

    - name: Trivy scan — client image
      uses: aquasecurity/trivy-action@master
      with:
        image-ref: pkhamdee/slotmachine:client-${{ github.sha }}
        severity: HIGH,CRITICAL
        exit-code: 1          # Fail the pipeline on HIGH or CRITICAL CVEs

    - name: Trivy scan — server image
      uses: aquasecurity/trivy-action@master
      with:
        image-ref: pkhamdee/slotmachine:server-${{ github.sha }}
        severity: HIGH,CRITICAL
        exit-code: 1

    - name: Push to Docker Hub       # Only on main branch
      if: github.ref == 'refs/heads/main'
      run: |
        docker push pkhamdee/slotmachine:client-${{ github.sha }}
        docker push pkhamdee/slotmachine:client
        docker push pkhamdee/slotmachine:server-${{ github.sha }}
        docker push pkhamdee/slotmachine:server

แต่ละ release push image tag 2 ตัว: - :client-abc1234 เป็น tag แบบ immutable ผูกกับ Git SHA ตัวเดียว Kustomize ใช้ตัวนี้ใน deployment manifest - :client เป็น tag แบบ mutable สไตล์ latest มีไว้ให้ใช้สะดวก

Trivy เอา OS package และ dependency ของภาษาใน container ไปเทียบกับฐานข้อมูล CVE เจอระดับ HIGH หรือ CRITICAL เมื่อไหร่ build fail ทันที image ตัวนั้นไม่มีทางขึ้น Docker Hub

Job 6: อัปเดต Deployment Repository

ตรงนี้ CI ส่งไม้ต่อให้ CD job สุดท้ายทำ 3 อย่าง: 1. Checkout slotmachine-deployment 2. ใช้ Kustomize เปลี่ยน image tag เป็น SHA ใหม่ 3. Commit แล้ว push ขึ้น branch development

update-gitops:
  needs: [container-build-scan-push]
  if: github.ref == 'refs/heads/main'
  runs-on: ubuntu-latest
  steps:
    - name: Checkout deployment repo
      uses: actions/checkout@v4
      with:
        repository: pkhamdee/slotmachine-deployment
        token: ${{ secrets.DEPLOYMENT_REPO_TOKEN }}
        ref: development

    - name: Update image tags
      run: |
        cd overlays/development
        kustomize edit set image \
          slotmachine-client=pkhamdee/slotmachine:client-${{ github.sha }}
        kustomize edit set image \
          slotmachine-server=pkhamdee/slotmachine:server-${{ github.sha }}

    - name: Commit and push
      run: |
        git config user.name  "github-actions[bot]"
        git config user.email "github-actions[bot]@users.noreply.github.com"
        git add .
        git commit -m "ci: update images to ${{ github.sha }}"
        git push origin development

push เสร็จ FluxCD ก็รับช่วงต่อ หน้าที่ของ CI จบตรงนี้


Part 4: Deployment Repository — Kustomize Base และ Overlay

Kubernetes manifest ทั้งหมดอยู่ใน repository slotmachine-deployment และจัดการด้วย Kustomize ซึ่งเป็น configuration tool แบบ Kubernetes-native เขียน base manifest ครั้งเดียว แล้ว patch แยกตาม environment

Layout ของ Repository

slotmachine-deployment/
├── base/                          ← Single source of truth for Kubernetes objects
│   ├── kustomization.yaml
│   ├── namespace.yaml
│   ├── client/
│   │   ├── deployment.yaml
│   │   ├── service.yaml
│   │   └── kustomization.yaml
│   ├── server/
│   │   ├── deployment.yaml
│   │   ├── service.yaml
│   │   ├── configmap.yaml
│   │   └── kustomization.yaml
│   ├── mongodb/
│   │   ├── statefulset.yaml       ← StatefulSet for stable Pod identity
│   │   ├── service.yaml
│   │   └── kustomization.yaml
│   └── redis/
│       ├── deployment.yaml
│       └── kustomization.yaml
└── overlays/
    ├── development/               ← Dev-specific patches
    │   ├── kustomization.yaml
    │   └── namespace.yaml
    └── production/                ← Prod-specific patches
        ├── kustomization.yaml
        └── namespace.yaml

Base — เขียนครั้งเดียว ใช้ได้ทุก Environment

Base วางโครงไว้พร้อมค่า default ที่ใช้ได้เลย ตัวอย่างเช่น base ของ server deployment:

# base/server/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: server
spec:
  replicas: 1                     # Overridden by overlays
  selector:
    matchLabels:
      app: slotmachine-server
  template:
    spec:
      initContainers:
        - name: wait-for-mongodb  # Don't start until DB is ready
          image: busybox
          command: ['sh', '-c',
            'until nc -z mongodb 27017; do sleep 2; done']
        - name: wait-for-redis
          image: busybox
          command: ['sh', '-c',
            'until nc -z redis 6379; do sleep 2; done']
      containers:
        - name: server
          image: slotmachine-server:latest   # Replaced by Kustomize
          ports:
            - containerPort: 3001
          envFrom:
            - configMapRef:
                name: server-config
            - secretRef:
                name: server-secret
          resources:
            requests:
              cpu: "200m"
              memory: "256Mi"
          readinessProbe:
            tcpSocket:
              port: 3001
          topologySpreadConstraints:
            - maxSkew: 1
              topologyKey: kubernetes.io/hostname
              whenUnsatisfiable: ScheduleAnyway
              labelSelector:
                matchLabels:
                  app: slotmachine-server

อย่ามองข้าม block initContainers ถ้าไม่มี server Pod จะ start ขึ้นมาก่อน MongoDB พร้อม แล้วก็ crash จากนั้น Kubernetes ก็ restart ให้วนไปไม่จบ init container ช่วยให้ dependency ขึ้นมาตามลำดับ แบบไม่ต้องเขียนโค้ดรอเอง

Overlay — Patch เฉพาะแต่ละ Environment

Production overlay แค่ patch ทับ base ไม่ต้อง copy มาทั้งไฟล์:

# overlays/production/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - ../../base

namespace: production

images:
  - name: slotmachine-client
    newName: pkhamdee/slotmachine
    newTag: client-abc1234def5    # ← auto-updated by CI
  - name: slotmachine-server
    newName: pkhamdee/slotmachine
    newTag: server-abc1234def5    # ← auto-updated by CI

patches:
  - target: { kind: Deployment, name: client }
    patch: |
      - op: replace
        path: /spec/replicas
        value: 4

  - target: { kind: Deployment, name: server }
    patch: |
      - op: replace
        path: /spec/replicas
        value: 6

  - target: { kind: StatefulSet, name: mongodb }
    patch: |
      - op: replace
        path: /spec/volumeClaimTemplates/0/spec/resources/requests/storage
        value: 20Gi

  - target: { kind: Service, name: client }
    patch: |
      - op: add
        path: /metadata/annotations
        value:
          service.beta.kubernetes.io/aws-load-balancer-type: "external"
          service.beta.kubernetes.io/aws-load-balancer-scheme: "internet-facing"

Development overlay โครงเหมือนกันเป๊ะ ต่างกันแค่ replica เป็น 1, storage 5Gi และไม่มี NLB annotation

ภาพรวมของสิ่งที่ Kustomize ทำให้:

                Base manifest
                     │
         ┌───────────┴───────────┐
         │                       │
    dev overlay             prod overlay
  replicas: 1              replicas: 4/6
  storage: 5Gi             storage: 20Gi
  namespace: development   namespace: production
  no NLB annotations       NLB + internet-facing

ไม่ต้อง copy-paste สักบรรทัด แก้ base manifest ทีเดียว (เช่น เพิ่ม environment variable ตัวใหม่) ทั้งสอง environment ได้ไปด้วยเลย


Part 5: FluxCD — CD Agent ที่ปิด Loop

FluxCD เป็น controller ชุดหนึ่งที่รันอยู่ในทุก Kubernetes cluster คอยดู branch ใน Git repository แล้ว reconcile cluster ให้ตรงกับที่ commit ไว้ตลอดเวลา

FluxCD ทำงานยังไง

FluxCD Poll Loop (every 1 minute by default):
  1. Connect to Git → fetch branch HEAD SHA
  2. Compare with last-applied SHA
  3. If different:
     a. git clone the new state
     b. kustomize build overlays/<env>/
     c. kubectl apply the rendered manifests
     d. Update last-applied SHA
  4. If same: nothing to do. Sleep. Repeat.

แบบนี้เรียกว่า pull-based CD cluster เป็นฝ่ายไปดึงจาก Git เอง ไม่ใช่ให้ pipeline push เข้ามา เทียบกันดูได้แบบนี้:

Push-based CD (traditional):
  CI runner → kubectl apply → cluster
  Problems:
  - CI runner needs cluster credentials
  - Cluster access from the internet
  - Hard to audit who changed what

Pull-based CD (GitOps with FluxCD):
  FluxCD (inside cluster) → polls Git → applies locally
  Advantages:
  - No external access to cluster needed
  - Cluster credentials never leave the cluster
  - Full audit trail in Git history
  - Self-healing: manual kubectl edits are reverted

Configuration ของ FluxCD สำหรับแต่ละ Environment

# flux-system/sources/slotmachine-deployment.yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
  name: slotmachine-deployment
  namespace: flux-system
spec:
  interval: 1m
  url: https://github.com/pkhamdee/slotmachine-deployment
  ref:
    branch: development    # ← development cluster watches 'development' branch
                           #   QA cluster watches 'qa' branch
                           #   Production cluster watches 'main' branch
  secretRef:
    name: flux-git-credentials
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: slotmachine
  namespace: flux-system
spec:
  interval: 5m
  sourceRef:
    kind: GitRepository
    name: slotmachine-deployment
  path: ./overlays/development   # ← path matches the cluster's environment
  prune: true                    # Delete resources removed from Git
  wait: true                     # Wait for rollout to complete
  healthChecks:
    - apiVersion: apps/v1
      kind: Deployment
      name: client
      namespace: development
    - apiVersion: apps/v1
      kind: Deployment
      name: server
      namespace: development

ตัวที่ต้องใส่ใจคือ prune: true ลบ manifest ออกจาก Git เมื่อไหร่ FluxCD ก็ลบ Kubernetes resource ตัวนั้นออกจาก cluster ด้วย cluster จึงตรงกับ Git เสมอ ไม่ขาดไม่เกิน

Self-Healing เวลาใช้งานจริง

Scenario: An engineer manually scales the server Deployment to 10 replicas
          with: kubectl scale deployment/server --replicas=10

FluxCD behavior (within 5 minutes):
  1. Detects drift: cluster has 10 replicas, Git says 6
  2. Re-applies the manifest from Git
  3. Cluster returns to 6 replicas
  4. Logs: "Kustomization/slotmachine: detected drift, reconciling"

Result: Manual changes to production are impossible to accidentally
        leave in place. Everything flows through Git.

Part 6: Multi-Environment Promotion — Human Gate

แต่ละ Git branch คือหนึ่ง environment:

Git branches in slotmachine-deployment:

  development  ──────────────────────────► K8s DEV  (Nutanix On-Premise)
      │
      │  Pull Request
      │  Reviewed by: DevOps/Platform Engineer
      ▼
     qa  ─────────────────────────────────► K8s QA   (Nutanix On-Premise)
      │
      │  Pull Request
      │  Reviewed by: QA Sign-Off process + Software Delivery Manager
      ▼
    main  ────────────────────────────────► K8s PROD (AWS EKS)

Release หนึ่งเดินทางผ่าน Pipeline ยังไง

Step 1 — Developer push ไปที่ main ใน app repo:

git push origin main
# → GitHub Actions CI starts (6 jobs, ~20 min)
# → On success: image tags written to development branch of deployment repo
# → FluxCD on DEV cluster detects change, deploys automatically

Step 2 — DevOps/Platform Engineer promote ขึ้น QA:

# In slotmachine-deployment repo:
# Create PR: development → qa
gh pr create \
  --base qa \
  --head development \
  --title "Release: app commit abc1234" \
  --body "Promoting $(git log development -1 --format='%s') to QA"
# DevOps Engineer reviews and approves
# PR merged → FluxCD on QA cluster detects change, deploys

Step 3 — QA Sign-Off และ Production Release:

QA team runs acceptance tests against QA cluster
  ↓
QA Sign-Off: test results recorded, sign-off documented
  ↓
Software Delivery Manager approves
  ↓
PR merged: qa → main
  ↓
FluxCD on Production cluster detects main branch change
  ↓
kustomize build overlays/production/
  ↓
kubectl apply → rolling update on AWS EKS
  (4 client pods × rolling update = zero downtime)
  (6 server pods × rolling update = zero downtime)

Promote ด้วย PR ไม่ใช่ Pipeline อีกเส้น

บางทีมเขียน script ให้ merge branch เองอัตโนมัติ แต่ architecture นี้เลือกใช้ PR โดยตั้งใจ เพราะ:

  • Visibility: ทุก promotion โผล่เป็น event ใน GitHub ค้นย้อนหลังได้ comment ได้ ผูกกับ issue ได้
  • Required review: Branch protection rule บังคับว่าต้องมีคน approve ก่อน merge
  • Rollback: จะ rollback production ก็แค่ git revert คำสั่งเดียวแล้ว merge ไม่ต้องเปิดขั้นตอน incident
  • Audit: ทุก promotion มี author, timestamp, reviewer และ message ครบ ใช้ตอบ compliance ได้เลย

Part 7: Infrastructure — Nutanix On-Premise และ AWS EKS

Kubernetes cluster 3 ตัวนี้กระจายอยู่บน infrastructure platform 2 แบบ แต่คุมจาก control plane ตัวเดียว

NKP Management Cluster (Nutanix Kubernetes Platform)

NKP Management Cluster รันบน hardware Nutanix on-premise และดูแลทั้ง DEV cluster และ QA cluster:

NKP Management Cluster (Nutanix On-Premise)
  │
  ├── SSO / IdP Integration
  │     → Single sign-on for cluster access
  │     → RBAC mapped to Active Directory groups
  │
  ├── Governance
  │     → Policy enforcement across managed clusters
  │     → Resource quotas, network policies, OPA Gatekeeper
  │
  ├── Platform Services
  │     → Centralized monitoring (Prometheus + Grafana)
  │     → Centralized logging (Loki / Elasticsearch)
  │     → Certificate management (cert-manager)
  │
  └── Application Services
        → Shared ingress controllers
        → Shared storage classes
        → Backup policies

Manages:
  ├── Kubernetes DEV  (Nutanix On-Premise)
  └── Kubernetes QA   (Nutanix On-Premise)

NKP มี management layer ที่สร้างบน Cluster API เราประกาศ DEV และ QA cluster ไว้แบบ declarative แล้ว management cluster คอยดูให้ทั้งคู่ตรงตาม spec เสมอ policy บังคับใช้ทั้ง fleet ถ้า cluster ไหน config ผิด management cluster จะเจอและแจ้งเตือนทันที

Production บน AWS EKS

Production รันบน AWS EKS ใน ap-southeast-7:

# Production cluster specifications
Nodes:      4× m6i.xlarge (4 vCPU, 16 GB RAM)
Zones:      ap-southeast-7a, ap-southeast-7b, ap-southeast-7c
CNI:        Cilium (SNAT mode)
LB:         AWS Network Load Balancer (cross-zone enabled)
Scheduling: topologySpreadConstraints (maxSkew: 1)

topologySpreadConstraints ใน base manifest กระจาย pod ให้เกลี่ยเท่า ๆ กันทุก node และทุก availability zone server pod 6 ตัวบน 4 node แปลว่า node ไหนพังไปตัวเดียว server pod หายไปไม่เกิน 2 ตัว

# From base/server/deployment.yaml
topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: kubernetes.io/hostname
    whenUnsatisfiable: ScheduleAnyway
    labelSelector:
      matchLabels:
        app: slotmachine-server

ทำไม Dev/QA อยู่ On-Premise แต่ Production อยู่บน Cloud?

Cost optimization:
  DEV/QA:  On-premise Nutanix hardware (already owned)
           → near-zero variable cost for non-production workloads
           → spin up/down as needed

  PROD:    AWS EKS
           → global availability
           → AWS NLB for internet-facing traffic
           → m6i.xlarge (cost-effective for the workload size)
           → auto-scaling when traffic spikes

Part 8: Security — Defense in Depth ทุก Stage

Pipeline นี้ใส่ security ไว้ตั้งแต่แรกในทุก phase ไม่ได้มาแปะเพิ่มตอนท้าย:

Stage         │ Tool           │ What It Catches
──────────────┼────────────────┼──────────────────────────────────────
Source code   │ CodeQL         │ SAST: injection, XSS, data flow vulns
Running app   │ OWASP ZAP      │ DAST: active attack simulation
Container OS  │ Trivy          │ CVEs in OS packages + npm dependencies
Runtime       │ K8s policies   │ Privilege escalation, host path mounts
Network       │ Cilium         │ Network policy enforcement between pods
Secrets       │ K8s Secrets    │ ADMIN_PASSWORD never in plaintext YAML
Headers       │ Express config │ CSP, X-Frame-Options, Permissions-Policy

Security Header ในโค้ด

// server/src/server.js — security headers applied at Express level
app.use((req, res, next) => {
  res.removeHeader('X-Powered-By');                    // Don't reveal Express
  res.setHeader('X-Frame-Options', 'DENY');            // Clickjacking
  res.setHeader('Content-Security-Policy',
    "default-src 'self'; script-src 'self'");          // XSS mitigation
  res.setHeader('Permissions-Policy',
    'camera=(), microphone=(), geolocation=()');       // Feature restriction
  next();
});

Container Hardening ด้วย Multi-Stage Build

# client/Dockerfile — two-stage: build then serve
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build             # Produces /app/dist

FROM nginx:alpine             # Final image has NO Node.js, NO source code
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Result: ~25MB image with zero Node.js attack surface

Client image ที่ได้มีแค่ Nginx กับ static file ที่ build เสร็จแล้ว Node.js runtime, npm และ source code ไม่ติดไปด้วยเลย


Part 9: Local Development — คำสั่งเดียวรันได้ทั้ง Stack

# docker-compose.yml
services:
  mongodb:
    image: mongo:7
    ports: ["27017:27017"]
    volumes:
      - mongo_data:/data/db

  redis:
    image: redis:7-alpine
    ports: ["6379:6379"]

  server:
    build: ./server
    ports: ["3001:3001"]
    environment:
      MONGO_URI: mongodb://mongodb:27017/slotmachine
      REDIS_URL: redis://redis:6379
      ADMIN_PASSWORD: localdev
    depends_on: [mongodb, redis]

  client:
    build: ./client
    ports: ["8080:80"]
    depends_on: [server]

volumes:
  mongo_data:
# Start the full stack locally
docker compose up --build

# Run the full test suite
npm ci && npm test --workspaces

# Run load test against local stack
locust -f tests/locustfile.py --headless -u 5 -r 1 -t 30s \
  --host http://localhost:8080

Local environment มี topology เหมือน production ทุกอย่าง ใช้ Nginx config ตัวเดียวกัน Redis adapter ตัวเดียวกัน และ MongoDB schema เดียวกัน รันบนเครื่องผ่านเมื่อไหร่ ขึ้น cluster ก็ผ่าน


Summary

Pipeline นี้เอาหลัก DevOps สมัยใหม่มาใช้ครบทุกข้อ ในระบบที่รันได้จริง

แยก slotmachine (application code) ออกจาก slotmachine-deployment (Kubernetes manifest) นี่คือฐานที่ทุกอย่างที่เหลือสร้างต่อขึ้นไป app กับ infrastructure เปลี่ยนแยกกันได้ audit trail สะอาด และแบ่งสิทธิ์ตาม role ได้ชัด developer push เข้า app repo ส่วน deployment repo เป็นของทีม platform

CI pipeline 6 job คุมคุณภาพและ security ทุก stage ก่อนจะมีอะไรหลุดไปถึง container registry CodeQL หาช่องโหว่ใน source code Vitest กับ node:test เช็คความถูกต้องด้วย 118 test Locust ยิงโหลดใส่ server ที่รันอยู่ OWASP ZAP ลองโจมตีจากข้างนอก Trivy scan หา CVE ใน container image ต้องผ่านครบ 6 gate ก่อน image ถึงจะขึ้น Docker Hub และ deployment repo ถึงจะได้ image tag ใหม่

FluxCD ปิด loop โดยรันอยู่ในแต่ละ cluster และคอย reconcile cluster ให้ตรงกับ Git branch ที่ดูอยู่ตลอดเวลา pipeline ไม่ต้องถือ credential เข้า cluster และไม่มีใครต้อง kubectl apply เอง cluster ซ่อมตัวเองได้ ถ้ามีอะไร drift ไปจาก desired state ใน Git จะกลับมาตรงเองในไม่กี่นาที

Promotion แบบ 3 branch (development → qa → main) ตรงกับ Kubernetes cluster 3 ตัว (Dev บน Nutanix, QA บน Nutanix, Production บน AWS EKS) human approval gate อยู่เฉพาะจุดที่มีคนตัดสินใจแล้วได้ประโยชน์ ไม่ได้ตัดคนออกจนหมด แต่ก็ไม่ได้ทำให้ delivery อัตโนมัติสะดุด

NKP management cluster ดูแล governance ทั้ง fleet ของ on-premise cluster ทั้ง SSO, policy ส่วนกลาง, observability และ platform service แต่ละ cluster ไม่ต้องสร้าง security และ monitoring stack ของตัวเองใหม่

สรุปคือ developer push feature แล้วเห็นขึ้น Dev ในไม่กี่นาที เปิด PR เพื่อ promote ขึ้น QA และพอ sign-off ก็ ship ขึ้น production บน AWS ได้เลย audit trail ครบ ไม่มีขั้นตอน manual ใน critical path และมี security อยู่ในทุก layer


Source code ทั้งหมดอยู่บน GitHub: slotmachine app · slotmachine-deployment มีคำถามหรืออยากคุยต่อ ทักมาได้ทาง LinkedIn, X หรือทาง email

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.