ข้ามไปยังเนื้อหา

Activity 07 — Developing Applications with Cloud Run: Fundamentals

คู่มืออ่านตาม Path · Activity 06 — GKE · บท Cloud Run · Lab map · Google Skills course

Activity นี้สอน Cloud Run resource model/container lifecycle/autoscaling, service identity/IAM, local development/testing และการเชื่อม Google Cloud services; syllabus แสดง hands-on least-privilege IAM bindings และ Pub/Sub integration โน้ตนี้เสริม course โดยไม่คัดลอก grader

📖 บทเรียนเต็ม: Cloud Run HTTP Service ตั้งแต่ Container ถึง Revision Rollback

หัวข้อที่มีชื่อว่า “📖 บทเรียนเต็ม: Cloud Run HTTP Service ตั้งแต่ Container ถึง Revision Rollback”

Cloud Run จัดการ Infrastructure/Scaling ในขอบเขต Service ให้ แต่ App Owner ยังรับผิดชอบ Container Image, Runtime Config, Memory/CPU, Concurrency, Identity, Network, Database Connections และ Security. Service เป็น Logical Endpoint, Revision เป็น Immutable Version ของ Deployment Configuration, Traffic Split เป็น Policy ที่กำหนดว่า Request ไป Revision ไหน. การ Rollback Traffic ไม่ Rollback Database Schema/Data

Container ต้องเริ่ม Process ที่ฟัง HTTP บน Port จาก Environment (ตาม Container Runtime Contract) และ Bind Address ที่ Platform เข้าถึงได้ ไม่ใช่แค่ 127.0.0.1. Error 503 หลัง Deploy อาจเกิดเพราะ Process Startup Fail, Secret/Config Missing, Revision Not Ready, Concurrency/Capacity หรือ Downstream Timeout

Identity ทำหน้าที่ สิทธิ์หลัก
Deployer สร้าง Service/Revision และส่ง Image Deployment/Service Administration ที่ได้รับอนุญาต
Invoker เรียก HTTP Endpoint run.routes.invoke ตาม Authorization Model
Runtime Service Account Process เรียก Cloud APIs, Cloud SQL, Pub/Sub Least Privilege บน Resources ที่ App ใช้
Service Agent Platform ใช้ทำงานตาม Service Google-managed Permission Scope

Ingress จำกัดประเภท Network Source/Route ส่วน Invoker IAM กำหนด Authorization. เปิด Internal Ingress ไม่ได้แปลว่าทุก Service ภายในมี Invoke Permission; เลือก Allow Unauthenticated ไม่ได้แปลว่า App Security เพียงพอ. วาง IAM/Network/Auth ตาม Trust Boundary

ตัวอย่าง App มี max instances=40, concurrency=50. ทางทฤษฎีอาจมี Requests กำลังประมวลผลพร้อมกันสูงได้ถึง 2000 ใน Service Config นี้ แต่ถ้า Database Accept Connections เพียง 80 และ App เปิด 1 Connection ต่อ Request จะเกิด Connection Saturation. ต้องรวม DB Pool, Request Duration, Cold Start, CPU Allocation, Retry Budget, Quota และ Cost เข้า Design. เพิ่ม Max Instances อย่างเดียวไม่ใช่ Scale Strategy

Traffic Rollout: Revision A 95%, B 5%. เฝ้า Error Rate, p95 Latency, Memory/CPU, DB Errors ของ B ก่อนเพิ่มเป็น 25%, 50%, 100%. ถ้า B Fail ให้ Rollback Traffic พร้อมตรวจ Schema Compatibility; ถ้า Migration เปลี่ยน DB และย้อนกลับไม่ได้ ต้องมี Expand/Contract Schema Strategy ก่อน Deploy

Terminal window
# Approved project only: no deploy, changes or traffic splitting.
gcloud run services list --region=REGION --project=LAB_PROJECT_ID
gcloud run services describe SERVICE_NAME --region=REGION --project=LAB_PROJECT_ID
gcloud run revisions list --service=SERVICE_NAME --region=REGION --project=LAB_PROJECT_ID

Expected: เห็น Service, Region, Ingress, Runtime SA, Revision Conditions, Traffic Allocation และ Scaling Settings ตามสิทธิ์. Actual: อ่านจาก Skills Lab หรือ Sandbox; คำสั่ง List อาจไม่โชว์ Resource ถ้าไม่มี Service หรือ IAM ไม่พอ; ห้าม Deploy เพียงเพื่อให้ Evidence ดูมีข้อมูล

  • 401/403: Auth/Invoker/Identity หรือ Ingress/Policy — อย่าทำ Service Public เพียงเพราะ Test ไม่ผ่าน
  • 503: Revision Not Ready, Startup Port, Container Crash, Backend/Resource Quota หรือ Downstream Timeout
  • Latency สูงแต่ Error ต่ำ: Concurrency, Cold Start, DB Pool, Network Calls, CPU/Memory Pressure
  • Revision B ผ่าน Health แต่ User เกิด Error บางส่วน: ดู Traffic Split, Route-specific Behavior, Request Logs/Dependencies

Case: New Revision คืน 503 พร้อม Log “cannot bind port”. ตรวจ App Listen Port/Bind Address และ Image Command ก่อนเพิ่ม CPU. หาก Error เป็น Cloud SQL Connection Timeout ต้องดู Runtime SA, Network, Connector, DB Connections แทน. วิธีแก้ต้องอิง Log ไม่ใช่เดาจาก HTTP Status อย่างเดียว

  1. Service กับ Revision ต่างกัน? — Service Stable, Revision Immutable Deployment Version
  2. Rollback Traffic ย้อน DB ไหม? — ไม่
  3. Max Instance x Concurrency ใหญ่ขึ้นช่วยเสมอไหม? — ไม่, DB/Downstream อาจอิ่มตัว
  4. Deployer IAM ส่งต่อ Runtime หรือไม่? — ไม่, คนละ Identity
  5. Internal Ingress แปลว่า Invoker Free ไหม? — ไม่, Auth แยก
  6. ทำไม 503 อาจมาจาก PORT? — Container Contract ต้องให้ Platform เรียก Listener ได้
  7. Runtime Secret อ่านไม่ได้แก้ด้วย Public Invoker ไหม? — ไม่; ต้องแก้ Secret/SA
  8. เมื่อไรเลือก Cloud Run แทน GKE? — HTTP/Events ที่ต้องการลด Node Operations และ Runtime Requirements รองรับ

Cloud Run Overview · Container Runtime · Traffic Management.


📎 ภาคขยาย: โครงเดิมและแบบฝึกเพิ่มเติม (ไม่จำเป็นต้องอ่านซ้ำ)

หัวข้อที่มีชื่อว่า “📎 ภาคขยาย: โครงเดิมและแบบฝึกเพิ่มเติม (ไม่จำเป็นต้องอ่านซ้ำ)”
  • เลือก Cloud Run service สำหรับ HTTP application และแยก service/revision/instance
  • เตรียม container ให้ทำงานตาม runtime contract
  • อธิบาย concurrency, autoscaling, minimum/maximum instances และ tradeoffs
  • แยก identity ของ deployer/build/runtime/caller
  • ตั้ง invoker access, ingress และ service-to-service auth ให้ตรง use case
  • จัด secrets/configuration โดยไม่ฝัง secret ใน source/image
  • deploy revision, ตรวจ health และเปลี่ยน/rollback traffic
  • เชื่อม Pub/Sub และออกแบบ retry/idempotency ให้ไม่ทำ side effect ซ้ำ
Module ขอบเขต
Fundamentals of Cloud Run resource model, container lifecycle, autoscaling, IAM access control
Service identity and authentication service accounts, resource hierarchy, least privilege, secrets/environment variables
Application development, testing and integration develop/test local, deployments/revisions, integrations
Hands-on Implementing Least Privilege IAM Policy Bindings in Cloud Run; Using Cloud Pub/Sub with Cloud Run

Service เป็น logical workload กับ stable endpoint/config; revision เป็น immutable snapshot ของ configuration/image/code เมื่อเปลี่ยน relevant config จะเกิด revision ใหม่; instance เป็น runtime instance ที่อาจ scale ตาม demand และ lifecycle policy

ข้อดีของ revision model คือ release แยกเป็นรุ่นและสามารถค่อย ๆ เปลี่ยน traffic ได้ แต่ state ใน local filesystem ไม่ใช่ persistent shared storage และแต่ละ revision อาจทำงานพร้อมกัน ต้องให้ compatible กับ database/API dependencies

Workload เริ่มพิจารณา
Stateless HTTP container ไม่ต้องการ Kubernetes API Cloud Run service
Background task ที่ทำจบแล้วหยุด Cloud Run job
Event handler/function code ตาม trigger Cloud Run functions
ต้องควบคุม Kubernetes objects, cluster/network policy GKE
ต้องควบคุม OS/VM process หรือ legacy runtime Compute Engine

Container ต้องเริ่ม process ที่ serve traffic ตาม runtime contract:

  • listen port ที่กำหนดโดย environment/config (มักอ่านจาก PORT)
  • bind address ที่รับ traffic จาก runtime เช่น 0.0.0.0 ไม่ใช่ loopback อย่างเดียว
  • process ต้อง start ภายในเวลาที่เหมาะกับ startup/health behavior
  • handle SIGTERM/shutdown ได้ดีเมื่อ instance ถูกหยุด
  • ไม่เก็บ durable state ไว้เฉพาะ local filesystem
  • logs ส่งไป stdout/stderr ให้ระบบรวบรวมได้ และห้าม log secrets

ทดสอบ container ในเครื่อง/CI ก่อน deploy: start, health path, port, env vars, startup failure, graceful shutdown และ dependency behavior

Cloud Run scale ตาม incoming traffic และ settings/metrics ที่รองรับ:

  • Concurrency: จำนวน concurrent requests ที่ instance รับได้ตาม setting; สูงขึ้นช่วยใช้ instance น้อยลงสำหรับ workload ที่ I/O bound แต่ CPU/memory/contention อาจทำ latency สูง
  • CPU/memory: เลือกให้เหมาะกับ request profile/startup/background needs และ pricing mode
  • Minimum instances: ช่วยลด cold-start ในบาง workload แต่มีค่าใช้จ่ายและไม่ได้ทำให้ทุก latency หาย
  • Maximum instances: จำกัด scale ตาม config; ช่วยปกป้อง downstream ได้ระดับหนึ่ง แต่ห้ามใช้แทน connection pooling/rate limiting/financial budget control
  • Request timeout: ต้องเหมาะกับงาน; งานยาวอาจควรเป็น job/async workflow

ตัวอย่างการคำนวณคร่าว ๆ: หากแต่ละ instance เปิด DB pool สูงสุด 15 connection และมีได้ 20 instances ก็อาจมี capacity ของ connection รวมถึง 300 ต่อ revision/service ตามการตั้งค่า อย่าคูณเฉพาะ concurrency แล้วลืม minimum/max instances และหลาย revisions ที่รับ traffic พร้อมกัน

Identity ใช้ทำอะไร ตัวอย่าง permission
Deployer deploy/ปรับ service และกำหนด runtime identity Cloud Run deploy permissions, actAs ที่จำเป็น
Build identity build source/image และ push artifact Cloud Build/Artifact Registry permissions ที่เกี่ยวข้อง
Runtime service account application เรียก Google APIs/อ่าน secret อ่านเฉพาะ resource/API ที่ app ต้องใช้
Invoker/caller ส่ง request ไปยัง private service Cloud Run Invoker บน service ตาม design
Google service agent platform ทำงานแทน managed service Google-managed permissions; อย่าลบ/แก้โดยไม่เข้าใจผล

การมีสิทธิ์ deploy ไม่ได้แปลว่าผู้เรียก service มีสิทธิ์ และ runtime SA ไม่ใช่ user ที่ใช้ gcloud deploy ทำ least-privilege bindings แยกตาม principal และ resource scope

  • Authentication/Invoker ระบุว่าใครเรียก service ได้
  • Ingress จำกัด network paths/sources ที่ service ยอมรับ
  • Application authorization ตรวจสิทธิ์ผู้ใช้ระดับ business logic

สามชั้นนี้ไม่ใช่สิ่งเดียวกัน: ingress ที่ internal ไม่ได้แทน authentication ของ caller และ Invoker permission ไม่ได้เปิดเส้นทาง network ที่ถูกจำกัดไว้

Service-to-service private call โดยทั่วไป caller ใช้ ID token ที่ audience เหมาะกับ service ปลายทางและ principal มีสิทธิ์ invoke ห้ามใส่ token ลง log หรือ hardcode ลง image

  • Environment variables เหมาะกับ config ที่ไม่ลับตามข้อกำหนดขององค์กร; ไม่ควรสมมติว่า env vars ทุกตัวเป็นความลับ
  • Secret Manager หรือการเชื่อม secret ที่รองรับ ใช้เก็บ secret พร้อมควบคุม access/rotation
  • จำกัด runtime SA ให้อ่าน secrets เฉพาะที่จำเป็น
  • ระวัง secret ใน build args, Dockerfile layers, shell history, CI logs และ error output
  • แยก dev/test/prod secrets และอย่า copy secret production ลง lab

เมื่อหมุน secret ให้เข้าใจ revision rollout/refresh semantics และ connection pool/cache ที่ application ใช้

ภาพ flow ขั้นต้น:

Publisher → Pub/Sub topic → subscription/trigger → Cloud Run handler
→ validate event → process idempotently → persist result → acknowledge/success

Cloud Run handler ต้องเตรียมรับ duplicate/retry ตาม delivery configuration และ trigger integration:

  • ทำ idempotency โดย event ID/business key + durable record/transaction เมื่อจำเป็น
  • แยก transient error (อาจ retry ได้) ออกจาก permanent invalid input
  • จำกัด retry/backoff/dead-letter behavior ตาม semantics ที่รองรับ
  • ส่ง success หลัง state transition สำคัญสำเร็จตาม design ไม่ใช่ก่อนเริ่มทำ
  • log event identifiers แบบไม่เผย payload ลับ
  • คิดเรื่อง concurrency และ downstream quotas/connection caps

Deploy revision ใหม่แบบไม่รับ trafficก่อน แล้วค่อยส่ง traffic ตามสัดส่วนจากเก่าไปใหม่เมื่อ health/metrics ผ่าน ใช้ revision history เพื่อ audit และ rollback traffic ได้ แต่ rollback ไม่ได้ย้อน database changes หรือ side effects

ตรวจ error rate, latency, startup failures, dependency metrics และ business signals; sample เล็กอาจสรุปผลไม่ได้ทันที ถ้า session affinity/traffic tags/traffic splits ถูกใช้ให้เข้าใจ behavior ปัจจุบัน

ดูตัวอย่างคำสั่งและข้อจำกัด canary เพิ่มใน Module 09 — Cloud Run

ทำตามโจทย์ใน Google Skills lab และกด checkpoint ที่นั่น; ไม่ใช้ project ส่วนตัวหาก lab จัด temporary project ให้

  • ระบุ deployer, runtime SA และ caller
  • ตรวจ role ที่จำเป็นสำหรับ deploy กับ invoke แยกกัน
  • ผูก Invoker กับ principal ตาม lab scope
  • กำหนด runtime identity และ permission สำหรับ service dependency
  • ทดสอบ permitted/denied calls ด้วย identity ที่ถูกต้อง
  • อ่าน 403 ว่าขาด invocation หรือ app-level permission ใด หลีกเลี่ยง broad grant
  • สร้าง topic/subscription หรือ trigger ตาม lab
  • ตรวจ identity ที่ trigger ใช้ส่ง request และ runtime identity ของ service
  • ส่ง test message/event และตรวจ Cloud Run logs/response
  • ทดสอบ failure/retry ตามโจทย์ โดยคิดถึง duplicate delivery
  • ยืนยันผล processing ด้วย state/output ที่ lab คาดหวัง

ทำ checklist app ของตัวเอง: listen PORT, bind 0.0.0.0, logs stdout, graceful shutdown, stateless storage, authentication model, env/secrets, concurrency/timeout และ DB connection pool

อาการ เริ่มตรวจ
Revision ไม่ Ready container logs, port/bind, startup, memory, health checks, dependency
401/403 ที่ endpoint caller identity/token audience, invoker IAM, ingress
App เรียก API ไม่ได้ runtime SA, target resource IAM, API enabled, VPC path
Secret อ่านไม่ได้ runtime principal, Secret Manager IAM, version/status, mount/env setup
Pub/Sub event ไม่เข้า topic/subscription/trigger config, trigger identity, region, permissions
Event ทำงานซ้ำ delivery/retry, idempotency storage, side effects
Latency/cold start สูง startup work, image size, dependencies, min instances/cpu settings
DB connections สูง instance count × pool limit × active revisions, max scaling, pooling strategy
Rollback แล้วระบบยังผิด data/schema changes, queued events/side effects, incompatible dependency
  1. Service, revision และ instance ต่างกันอย่างไร?
  2. Runtime service account ต่างจาก deployer และ invoker อย่างไร?
  3. Ingress internal แทน IAM authentication ได้หรือไม่?
  4. ทำไม Cloud Run local filesystem ไม่เหมาะกับ durable shared state?
  5. เพิ่ม concurrency แล้ว connection count หรือ latency อาจเปลี่ยนอย่างไร?
  6. Pub/Sub ส่ง event ซ้ำได้; app ควรออกแบบอย่างไร?
  7. Traffic rollback คืน database/schema ได้หรือไม่?

เฉลยย่อ: service เป็น logical endpoint, revision เป็น version/config snapshot, instance เป็น runtime process; identities ทำคนละหน้าที่; ingress ไม่ใช่ auth; local file ไม่ durable/shared; concurrency กระทบ resource pressure; handlers ควร idempotent และมี retry policy; traffic rollback ไม่ย้อน data migration

flowchart LR
 C[HTTP client] --> I[Ingress policy]
 I --> A{Caller authorized?}
 A -->|Yes| S[Cloud Run service]
 A -->|No| X[403 or 401]
 S --> R1[Revision A 90 percent]
 S --> R2[Revision B 10 percent]
 R1 --> DB[Downstream database]
 R2 --> DB

Cloud Run Service เป็น Stable Endpoint ที่ Route Traffic ไปยัง Revisions ซึ่งเป็น Immutable Deployment Config Snapshot. การ Roll Back Traffic ไม่ได้ย้อน Database Schema Change หรือ State ภายนอกโดยอัตโนมัติ. App ต้อง Listen ตาม Runtime PORT ที่ Platform กำหนดและ Bind 0.0.0.0 ตาม Container Contract; ถ้า Listen 127.0.0.1 อย่างเดียว Health Startup อาจล้มเหลว

  1. Deployer: User หรือ CI Pipeline ที่สร้าง/เปลี่ยน Service และส่ง Image
  2. Invoker: Caller ที่มี run.routes.invoke หรือสิทธิ์การเรียก Service ตาม Auth Model
  3. Runtime Service Account: Identity ที่ Code ใช้เข้าถึง Cloud SQL, Pub/Sub หรือ Cloud Storage

IAM Invoker และ Ingress เป็นคนละ Control: Ingress กรองเส้นทาง Network ที่อนุญาต; Authentication/Authorization ตัดสิน Identity ของ Caller. แค่ตั้ง Ingress Internal ไม่ได้ทำให้ทุก Internal Client มีสิทธิ์ Invoker โดยอัตโนมัติ

3. Cost/Performance: Max instances และ Concurrency ไม่ใช่ปุ่มช่วยได้ทุกกรณี

หัวข้อที่มีชื่อว่า “3. Cost/Performance: Max instances และ Concurrency ไม่ใช่ปุ่มช่วยได้ทุกกรณี”

การเพิ่ม concurrency ช่วยรวม Requests ต่อ Instance ได้ แต่ App ที่ทำ CPU-bound หรือต่อ Database แบบ One Connection per Request อาจเพิ่ม Tail Latency/Database Saturation แทน. หากมี 1000 Concurrent HTTP Requests และ Database Connection Limit 80, การเพิ่ม Max Instances แบบไม่ควบคุมอาจทำให้ทุก Revision แย่ง Connection กัน

Sample design (illustrative): Service รับ 600 Requests/Second, p95 Latency เป้าหมาย 400 ms. เลือก Concurrency จาก Load Test + Memory/CPU Per Request, ไม่ใช้เพียงตัวเลข Default. เตรียม Downstream Rate Limit และ Retry with Backoff

ตรวจ Traffic Split → Revision Ready Condition → Container Startup Logs → PORT/Listen Address → Secret Binding → IAM Runtime Identity → Cloud SQL Connector/Network → Max Instances/Quota. ห้าม Rollout ไป 100% หรือบังคับ Public Invoker เพื่อ “ดูว่าหายไหม” โดยไม่รู้ Root Cause

Terminal window
# Read-only, approved project only:
gcloud run services describe SERVICE_NAME --region=REGION --project=LAB_PROJECT_ID
gcloud run revisions list --service=SERVICE_NAME --region=REGION --project=LAB_PROJECT_ID

Official: Cloud Run Container Runtime · Traffic Management · Securing Services.

Checkpoint: อธิบายความต่างระหว่าง Ingress, Invoker, Runtime SA และ Revision Traffic Split ได้โดยไม่ต้องเปิด Module อื่น


เรียนบทหลักตามลำดับ ส่วนลิงก์ด้านล่างเป็นเนื้อหาเสริมหรือแบบฝึก ไม่จำเป็นต้องทำทั้งหมดก่อนบทถัดไป หากต้องการเจาะลึกหรือลงมือทำ ให้เลือกเปิดเฉพาะสิ่งที่เกี่ยวข้องกับเป้าหมาย

📚 Modules — เจาะลึกตามหัวข้อ

🧪 Companion Labs — ไม่ใช่ Official Google Skills Grader

🗺️ ตารางจับคู่ Activities / Modules / Labs

✅ บทที่ 7/17 ในเส้นทางหลัก

เมื่ออ่านและฝึกทบทวนจบแล้ว ทำเครื่องหมายเพื่อบันทึกใน Browser นี้