Module 11 Public Cloud 5 labs

Google Cloud Platform Core for DevOps

Nắm vững nền tảng GCP dành cho DevOps Engineer: IAM, VPC, Compute Engine, Cloud Storage, GKE, Cloud Run, Artifact Registry và Cloud Monitoring — toàn bộ qua gcloud CLI thực tế.

Công cụ thực hành gcloud CLI, kubectl, Docker, Cloud Console
Nền tảng Google Cloud Platform, Cloud Shell / Linux / WSL2
Thời điểm phát hành 23/05/2026
Ngày biên soạn 23/05/2026
Người biên soạn Trần Văn Hòa — Microsoft Certified Trainer (MCT)

Mục tiêu học tập

1. Lý thuyết cốt lõi

1.1. GCP Resource Hierarchy & IAM

GCP tổ chức tài nguyên theo cây phân cấp: Organization (gốc, thường là domain G Suite/Cloud Identity) → Folder (nhóm dự án theo team/env) → Project (đơn vị billing và quản lý API) → Resource (VM, bucket, …). Policy IAM kế thừa từ trên xuống — đây là điểm khác biệt quan trọng so với Azure RBAC.

IAM: Principal → Role → Permission

  • Principal: Google Account, Service Account, Group, Domain, allUsers.
  • Role types: Basic (Owner/Editor/Viewer — tránh dùng production), Predefined (ví dụ roles/container.developer), Custom.
  • Service Account: identity cho workload — gắn SA vào VM/GKE node pool thay vì nhúng key JSON.
  • Workload Identity Federation: cho phép workload bên ngoài (GitHub Actions, AWS, on-prem) impersonate SA mà không cần key.

1.2. Networking: VPC, Subnet, Firewall, Cloud NAT

GCP VPC là global — một VPC có subnet ở nhiều region, khác với AWS/Azure (VPC/VNet per-region). Mặc định có default VPC nhưng production nên dùng custom mode VPC để kiểm soát CIDR. Firewall rule là stateful, gắn vào VPC không phải subnet; áp dụng qua network tag hoặc service account. Cloud NAT cung cấp outbound internet cho VM không có external IP.

Thành phầnĐặc điểm GCPTương đương AWS/Azure
VPCGlobal, cross-region subnetVPC (per-region) / VNet
FirewallVPC-level, tag/SA-basedSecurity Group / NSG
Cloud NATManaged outbound NATNAT Gateway
Cloud DNSManaged DNS, private zoneRoute 53 / Azure DNS

1.3. Compute Engine, Cloud Storage & Managed Services

Compute Engine là IaaS — VM chạy trên KVM, hỗ trợ custom machine type, preemptible/spot VM, live migration. Cloud Storage là object store toàn cầu với 4 storage class (Standard, Nearline, Coldline, Archive); hỗ trợ signed URL, Lifecycle policy, Uniform bucket-level access. Cloud SQL / Spanner / Firestore / BigQuery là lớp managed database.

1.4. GKE — Google Kubernetes Engine

GKE là managed Kubernetes với control plane do Google vận hành (miễn phí với Autopilot; tính phí với Standard). Hai chế độ: Standard (bạn quản lý node pool) và Autopilot (Google quản lý toàn bộ node). GKE tích hợp sẵn: Workload Identity (SA mapping), Binary Authorization, GCP Load Balancer (NEG), Cloud Logging/Monitoring, Artifact Registry.

1.5. Cloud Run & Artifact Registry

Cloud Run là serverless container platform (PaaS) — deploy bất kỳ container HTTP nào, scale-to-zero, billing per-request. Phù hợp microservice, API backend, batch job. Artifact Registry thay thế Container Registry; hỗ trợ Docker, Maven, npm, Python, Go — cùng region với workload để giảm latency và egress cost.

1.6. Cloud Monitoring & Logging

GCP Observability stack: Cloud Monitoring (metrics, uptime check, alerting, dashboards), Cloud Logging (structured log, log sink → BigQuery/Pub-Sub/Storage), Cloud Trace (distributed tracing), Cloud Profiler (CPU/memory profiling). Metric tùy chỉnh qua OpenTelemetry hoặc Prometheus scraping trên GKE.

2. Thực hành (Labs)

LAB-051

IAM, Service Account & Custom VPC bằng gcloud

gcloud CLI · Cloud Console

🎯 Mục tiêu: Tạo project, custom VPC, subnet; tạo Service Account với role tối thiểu; gán role IAM cho user.

🧰 Công cụ / nền tảng: gcloud CLI (hoặc Cloud Shell), tài khoản GCP có billing.

📦 Chuẩn bị: Cài gcloud SDK (gcloud --version); chạy gcloud auth logingcloud auth application-default login.

▶️ Các bước (CLI):

# 1. Tạo project mới (thay PROJECT_ID bằng ID duy nhất)
export PROJECT_ID="htlab-devops-m11"
gcloud projects create $PROJECT_ID --name="HTLab DevOps M11"
gcloud config set project $PROJECT_ID

# 2. Bật billing (thay BILLING_ACCOUNT_ID)
# gcloud billing projects link $PROJECT_ID --billing-account=BILLING_ACCOUNT_ID

# 3. Bật các API cần thiết
gcloud services enable compute.googleapis.com \
  container.googleapis.com \
  artifactregistry.googleapis.com \
  run.googleapis.com \
  monitoring.googleapis.com \
  logging.googleapis.com

# 4. Tạo custom VPC (không tự tạo subnet)
gcloud compute networks create htlab-vpc \
  --subnet-mode=custom \
  --bgp-routing-mode=regional

# 5. Tạo subnet cho ứng dụng (asia-southeast1 = Singapore)
gcloud compute networks subnets create htlab-app-subnet \
  --network=htlab-vpc \
  --region=asia-southeast1 \
  --range=10.10.1.0/24 \
  --enable-private-ip-google-access

# 6. Tạo firewall rule: cho phép SSH từ IAP
gcloud compute firewall-rules create allow-iap-ssh \
  --network=htlab-vpc \
  --allow=tcp:22 \
  --source-ranges=35.235.240.0/20 \
  --description="Allow SSH via IAP"

# 7. Tạo firewall rule: cho phép HTTP internal
gcloud compute firewall-rules create allow-internal-http \
  --network=htlab-vpc \
  --allow=tcp:80,tcp:8080,tcp:443 \
  --source-tags=allow-http \
  --target-tags=web-server

# 8. Tạo Service Account cho ứng dụng (least privilege)
gcloud iam service-accounts create htlab-app-sa \
  --display-name="HTLab App Service Account"

SA_EMAIL="htlab-app-sa@${PROJECT_ID}.iam.gserviceaccount.com"

# 9. Gán role tối thiểu (chỉ đọc Storage)
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:${SA_EMAIL}" \
  --role="roles/storage.objectViewer"

# 10. Kiểm tra IAM policy
gcloud projects get-iam-policy $PROJECT_ID \
  --flatten="bindings[].members" \
  --format="table(bindings.role,bindings.members)" | grep htlab

🖥️ Đối chiếu GUI (Cloud Console):

IAM & Admin → IAM: xem binding; VPC network → VPC networks: kiểm tra htlab-vpc và subnet; Firewall: kiểm tra 2 rule vừa tạo.

✅ Kết quả mong đợi: gcloud compute networks describe htlab-vpc ra subnetMode: CUSTOM; gcloud iam service-accounts list thấy htlab-app-sa; policy binding hiển thị role storage.objectViewer.

🧹 Cleanup:

# Giữ lại project, subnet dùng cho LAB-052 đến LAB-055
# Sau khi hoàn thành toàn bộ module, xóa project:
# gcloud projects delete $PROJECT_ID
LAB-052

Deploy Compute Engine VM & Cloud Storage

gcloud CLI · gsutil / gcloud storage

🎯 Mục tiêu: Tạo VM Compute Engine không có external IP (chỉ IAP SSH), mount Cloud Storage bucket, cấu hình startup script.

🧰 Công cụ / nền tảng: gcloud CLI, gsutil/gcloud storage.

📦 Chuẩn bị: Hoàn thành LAB-051; biến PROJECT_IDSA_EMAIL đã set.

▶️ Các bước (CLI):

# 1. Tạo Cloud Storage bucket (tên bucket phải globally unique)
BUCKET="htlab-assets-${PROJECT_ID}"
gcloud storage buckets create gs://${BUCKET} \
  --location=asia-southeast1 \
  --uniform-bucket-level-access

# 2. Upload file test
echo "Hello from GCS bucket" > index.html
gcloud storage cp index.html gs://${BUCKET}/index.html

# 3. Kiểm tra object
gcloud storage ls gs://${BUCKET}

# 4. Tạo VM không có external IP, gắn SA, có network tag
gcloud compute instances create htlab-web-01 \
  --zone=asia-southeast1-a \
  --machine-type=e2-micro \
  --subnet=htlab-app-subnet \
  --no-address \
  --service-account=${SA_EMAIL} \
  --scopes=cloud-platform \
  --tags=web-server \
  --image-family=debian-12 \
  --image-project=debian-cloud \
  --metadata=startup-script='#!/bin/bash
apt-get update -y
apt-get install -y nginx
systemctl enable nginx
systemctl start nginx
echo "

HTLab GCE VM - $(hostname)

" > /var/www/html/index.html' # 5. Kiểm tra VM đang chạy gcloud compute instances describe htlab-web-01 \ --zone=asia-southeast1-a \ --format="table(name,status,networkInterfaces[0].networkIP)" # 6. SSH qua IAP (không cần external IP, không cần open port 22 to internet) gcloud compute ssh htlab-web-01 \ --zone=asia-southeast1-a \ --tunnel-through-iap # Bên trong VM kiểm tra nginx # curl localhost # exit # 7. Cấu hình Lifecycle policy cho bucket (tự xóa object sau 30 ngày) cat > lifecycle.json <<'EOF' { "lifecycle": { "rule": [{ "action": {"type": "Delete"}, "condition": {"age": 30} }] } } EOF gcloud storage buckets update gs://${BUCKET} \ --lifecycle-file=lifecycle.json

🖥️ Đối chiếu GUI (Cloud Console):

Compute Engine → VM instances: thấy htlab-web-01 status Running, no External IP. Cloud Storage → Buckets: thấy bucket và lifecycle rule.

✅ Kết quả mong đợi: VM status RUNNING; SSH qua IAP thành công; curl localhost bên trong VM trả về HTML nginx; bucket có object index.html và lifecycle rule.

🧹 Cleanup:

# Giữ lại để tham khảo; hoặc xóa VM nếu muốn tiết kiệm chi phí:
gcloud compute instances delete htlab-web-01 --zone=asia-southeast1-a --quiet
LAB-053

Artifact Registry & push/pull Docker image

gcloud CLI · Docker

🎯 Mục tiêu: Tạo Artifact Registry repository, build Docker image, push lên registry, scan vulnerability cơ bản.

🧰 Công cụ / nền tảng: gcloud CLI, Docker Desktop (hoặc Docker Engine trên Linux/WSL2).

📦 Chuẩn bị: Docker đã cài; docker --version chạy được.

▶️ Các bước (CLI):

# 1. Tạo Artifact Registry repo kiểu Docker
REGION="asia-southeast1"
REPO="htlab-docker"

gcloud artifacts repositories create ${REPO} \
  --repository-format=docker \
  --location=${REGION} \
  --description="HTLab Docker registry M11"

# 2. Cấu hình Docker credential helper cho registry
gcloud auth configure-docker ${REGION}-docker.pkg.dev

# 3. Tạo ứng dụng mẫu
mkdir htlab-app && cd htlab-app

cat > app.py <<'EOF'
from http.server import HTTPServer, BaseHTTPRequestHandler

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(b"HTLab GCP App v1.0 - Module 11\n")

HTTPServer(("", 8080), Handler).serve_forever()
EOF

cat > Dockerfile <<'EOF'
FROM python:3.12-slim
WORKDIR /app
COPY app.py .
EXPOSE 8080
CMD ["python", "app.py"]
EOF

# 4. Build image với tag đầy đủ cho Artifact Registry
IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/htlab-app:v1.0"
docker build -t ${IMAGE} .

# 5. Push lên Artifact Registry
docker push ${IMAGE}

# 6. Liệt kê image trong registry
gcloud artifacts docker images list ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}

# 7. (Tùy chọn) Bật Container Analysis / Vulnerability Scanning tự động
gcloud services enable containerscanning.googleapis.com
# Sau khi push, kết quả scan xuất hiện trong Cloud Console:
# Artifact Registry → htlab-docker → htlab-app:v1.0 → Security

cd .. && rm -rf htlab-app

🖥️ Đối chiếu GUI (Cloud Console):

Artifact Registry → Repositories: thấy htlab-docker; click vào xem image htlab-app:v1.0 với digest SHA256 và vulnerability summary.

✅ Kết quả mong đợi: docker push thành công; gcloud artifacts docker images list trả về image với digest; tab Security trong Console hiển thị kết quả scan.

🧹 Cleanup:

# Xóa image (giữ repo cho LAB-054/055):
gcloud artifacts docker images delete \
  "${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/htlab-app:v1.0" --quiet
LAB-054

Deploy Cloud Run service từ Artifact Registry

gcloud CLI · Cloud Console · Cloud Run

🎯 Mục tiêu: Deploy container lên Cloud Run, cấu hình concurrency, scaling, biến môi trường và domain mapping.

🧰 Công cụ / nền tảng: gcloud CLI, Cloud Run (managed), Docker.

📦 Chuẩn bị: Hoàn thành LAB-053; image đã có trong Artifact Registry.

▶️ Các bước (CLI):

REGION="asia-southeast1"
REPO="htlab-docker"
IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/htlab-app:v1.0"

# Nếu đã xóa image ở LAB-053, build và push lại:
mkdir htlab-app && cd htlab-app
cat > app.py <<'EOF'
from http.server import HTTPServer, BaseHTTPRequestHandler
import os

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        env = os.environ.get("APP_ENV", "production")
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(f"HTLab Cloud Run | env={env} | host={self.headers.get('Host')}\n".encode())

HTTPServer(("", 8080), Handler).serve_forever()
EOF
cat > Dockerfile <<'EOF'
FROM python:3.12-slim
WORKDIR /app
COPY app.py .
EXPOSE 8080
CMD ["python", "app.py"]
EOF
docker build -t ${IMAGE} . && docker push ${IMAGE}
cd .. && rm -rf htlab-app

# 1. Deploy lên Cloud Run (công khai — allow unauthenticated)
gcloud run deploy htlab-app \
  --image=${IMAGE} \
  --platform=managed \
  --region=${REGION} \
  --allow-unauthenticated \
  --port=8080 \
  --min-instances=0 \
  --max-instances=5 \
  --concurrency=80 \
  --set-env-vars="APP_ENV=production" \
  --service-account=${SA_EMAIL}

# 2. Lấy URL service
SERVICE_URL=$(gcloud run services describe htlab-app \
  --platform=managed \
  --region=${REGION} \
  --format="value(status.url)")
echo "Service URL: ${SERVICE_URL}"

# 3. Kiểm tra endpoint
curl -s ${SERVICE_URL}

# 4. Deploy revision mới (canary 20% traffic)
gcloud run deploy htlab-app \
  --image=${IMAGE} \
  --platform=managed \
  --region=${REGION} \
  --no-traffic \
  --tag=v2

gcloud run services update-traffic htlab-app \
  --platform=managed \
  --region=${REGION} \
  --to-tags=v2=20,LATEST=80

# 5. Xem danh sách revision và traffic split
gcloud run revisions list \
  --service=htlab-app \
  --platform=managed \
  --region=${REGION} \
  --format="table(metadata.name,status.conditions[0].type,spec.containerConcurrency)"

🖥️ Đối chiếu GUI (Cloud Console):

Cloud Run → htlab-app: tab Revisions hiển thị traffic split 80/20; tab Metrics: request count, latency, instance count.

✅ Kết quả mong đợi: curl ${SERVICE_URL} trả về text có env=production; Revisions tab thấy 2 revision với traffic 80/20; scale-to-zero khi không có traffic (instance count = 0 sau >5 phút idle).

🧹 Cleanup:

gcloud run services delete htlab-app --platform=managed --region=${REGION} --quiet
LAB-055

GKE Cluster, Workload Deploy & Cloud Monitoring Alert

gcloud CLI · kubectl · Helm · Cloud Monitoring

🎯 Mục tiêu: Tạo GKE Standard cluster, deploy ứng dụng bằng kubectl, tạo uptime check và alert policy trên Cloud Monitoring.

🧰 Công cụ / nền tảng: gcloud CLI, kubectl, Helm 3, Cloud Monitoring.

📦 Chuẩn bị: kubectl cài sẵn; Helm 3 cài sẵn; hoàn thành LAB-053 (image trong registry).

▶️ Các bước (CLI):

REGION="asia-southeast1"
ZONE="${REGION}-a"
REPO="htlab-docker"
IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/htlab-app:v1.0"

# 1. Tạo GKE Standard cluster (e2-medium, 2 node để tiết kiệm)
gcloud container clusters create htlab-cluster \
  --zone=${ZONE} \
  --num-nodes=2 \
  --machine-type=e2-medium \
  --network=htlab-vpc \
  --subnetwork=htlab-app-subnet \
  --workload-pool=${PROJECT_ID}.svc.id.goog \
  --enable-ip-alias \
  --no-enable-basic-auth \
  --release-channel=regular

# Cluster tạo mất ~5 phút. Theo dõi:
gcloud container clusters list

# 2. Lấy kubeconfig
gcloud container clusters get-credentials htlab-cluster \
  --zone=${ZONE}

# 3. Kiểm tra kết nối cluster
kubectl get nodes -o wide
kubectl get namespaces

# 4. Deploy ứng dụng
kubectl create namespace htlab

kubectl create deployment htlab-app \
  --image=${IMAGE} \
  --namespace=htlab \
  --replicas=2

kubectl expose deployment htlab-app \
  --type=LoadBalancer \
  --port=80 \
  --target-port=8080 \
  --namespace=htlab

# 5. Đợi LoadBalancer IP (1-3 phút)
kubectl get svc htlab-app -n htlab -w
# Ctrl+C khi EXTERNAL-IP xuất hiện

LB_IP=$(kubectl get svc htlab-app -n htlab -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
curl http://${LB_IP}

# 6. Scale up và kiểm tra rolling update
kubectl scale deployment htlab-app --replicas=4 -n htlab
kubectl rollout status deployment/htlab-app -n htlab

# 7. Tạo uptime check qua Cloud Monitoring
gcloud monitoring uptime-checks create \
  --display-name="HTLab App Uptime" \
  --resource-type=uptime-url \
  --hostname=${LB_IP} \
  --path="/" \
  --check-interval=60s \
  --timeout=10s \
  --regions=asia-pacific

# 8. Tạo Notification Channel (email) — dùng Console hoặc API
# Cloud Monitoring → Alerting → Notification Channels → Add email

# 9. Tạo Alert Policy: cảnh báo khi uptime check fail
gcloud alpha monitoring policies create \
  --display-name="HTLab Uptime Alert" \
  --condition-display-name="Uptime fail" \
  --condition-filter='resource.type="uptime_url" AND metric.type="monitoring.googleapis.com/uptime_check/check_passed"' \
  --condition-threshold-value=1 \
  --condition-threshold-comparison=COMPARISON_LT \
  --condition-duration=60s \
  --combiner=OR

# 10. Xem metrics cluster
kubectl top nodes
kubectl top pods -n htlab

🖥️ Đối chiếu GUI (Cloud Console):

Kubernetes Engine → Workloads: thấy deployment htlab-app với 4 pod; Services & Ingress: thấy LoadBalancer IP. Cloud Monitoring → Uptime checks: thấy check với trạng thái pass/fail.

✅ Kết quả mong đợi: kubectl get pods -n htlab thấy 4 pod trạng thái Running; curl http://${LB_IP} trả về response; Cloud Monitoring Uptime check trạng thái Passing.

🧹 Cleanup:

# Xóa cluster (tránh chi phí node VM)
gcloud container clusters delete htlab-cluster --zone=${ZONE} --quiet

# Xóa toàn bộ project sau khi học xong:
# gcloud projects delete $PROJECT_ID --quiet

3. Tình huống doanh nghiệp thực tế

Bối cảnh: Startup fintech tại Việt Nam mở rộng sang Đông Nam Á

Một startup fintech với 20 engineers dùng monolith on GCE, muốn chuyển sang microservices để release độc lập từng module (payment, KYC, notification). Yêu cầu: latency <200ms cho user SEA, chi phí có thể dự đoán, zero-downtime deploy.

Thiết kế giải pháp (GCP)

  • IAM: Mỗi service có Service Account riêng với role tối thiểu; Workload Identity cho GKE pods — không dùng key JSON.
  • Network: Custom VPC với subnet riêng cho prod/staging/dev; Private Google Access để GCE/GKE gọi GCP API qua internal.
  • Compute: GKE Autopilot cho microservices (Google quản lý node); Cloud Run cho API nhẹ và event-driven job (KYC webhook).
  • Artifact Registry: Một registry per region (asia-southeast1 + asia-east1) để giảm pull latency; Vulnerability Scanning auto bật.
  • Observability: Cloud Monitoring với SLO dashboard (availability + latency); Log sink → BigQuery để phân tích audit trail; Cloud Trace cho distributed tracing giữa các service.
  • Kết quả: Deploy frequency tăng từ 2 lần/tháng lên 10 lần/tuần; MTTR giảm nhờ alert policy tự động; chi phí giảm 30% nhờ scale-to-zero Cloud Run và Autopilot node provisioning.

📚 Nguồn tham khảo

Module 10: Azure Core Module 12: Hybrid Cloud Design
Zalo