Skip to content

Migrate từ Standard sang Autopilot

Tại sao migrate và khi nào không nên

Lý do migrate

Các tổ chức migrate sang Autopilot thường vì:

  • Giảm operational overhead: Không còn quản lý node pools, upgrades, và capacity planning
  • Cost optimization: Bill theo actual Pod resources thay vì idle node capacity
  • Security baseline tốt hơn: Autopilot enforce security defaults mà Standard không có
  • Simplify platform: Bỏ bớt tầng abstraction giữa developer và Kubernetes

Khi nào không nên migrate

Giữ nguyên Standard nếu:

  • Workloads cần privileged containers không có trong Autopilot allowlist
  • Cần custom DaemonSets cho logging/monitoring (Datadog agent tùy chỉnh, custom Falco)
  • Workloads cần kernel tuning (huge pages, net.core.somaxconn, custom sysctl)
  • Chạy platform tooling phức tạp (CNI plugins, storage drivers) cần node-level access
  • Compliance yêu cầu sole-tenant nodes hoặc Windows node pools
  • Team muốn fine-grained control về node placement và machine types

Đánh giá trung thực: Migrate sang Autopilot là đúng đắn cho nhiều teams, nhưng không phải mọi workload. Đừng migrate vì "xu hướng" — migrate khi nó thực sự giải quyết pain points của bạn.

Bước 1: Pre-flight check

GKE cung cấp công cụ pre-flight check tự động để phát hiện incompatibilities:

bash
# Enable pre-flight check component (GKE 1.31.6+ yêu cầu explicit enablement)
gcloud container clusters update SOURCE_CLUSTER \
  --region REGION \
  --update-addons=GcpFilestoreCsiDriver=ENABLED  # Một số addons cần enable

# Chạy compatibility check
gcloud container clusters check-autopilot-compatibility SOURCE_CLUSTER \
  --region REGION

# Output chi tiết
gcloud container clusters check-autopilot-compatibility SOURCE_CLUSTER \
  --region REGION \
  --format=json > compatibility-report.json

Kết quả chia thành 4 categories:

CategoryÝ nghĩaHành động
PassedTương thích hoàn toànKhông cần làm gì
Passed with optional configHoạt động nhưng có thể optimizeReview và quyết định
Additional config requiredPhải thay đổi mới hoạt độngSửa trước khi migrate
IncompatibilityKhông hỗ trợ trong AutopilotKhông migrate hoặc thay thế workload

Bước 2: Incompatibility checklist

Dưới đây là danh sách các vấn đề phổ biến và cách giải quyết:

1. Privileged containers

Vấn đề:

yaml
# Standard: Hoạt động
spec:
  containers:
  - name: init
    securityContext:
      privileged: true

Giải pháp:

  • Kiểm tra xem container có thực sự cần privileged: true không
  • Nhiều trường hợp chỉ cần capabilities cụ thể: CAP_SYS_ADMIN, CAP_NET_ADMIN
  • Nếu workload là vendor tool, kiểm tra vendor có Autopilot-compatible version không
yaml
# Sau khi optimize
spec:
  containers:
  - name: init
    securityContext:
      privileged: false
      capabilities:
        add:
        - NET_ADMIN  # Chỉ add capability cần thiết

2. Custom DaemonSets

Vấn đề: DaemonSets tùy chỉnh (không phải Google/verified partners) bị reject trong Autopilot.

Giải pháp theo use case:

Use caseStandard approachAutopilot alternative
LoggingFluentd DaemonSetGKE managed logging tự động
MonitoringNode Exporter DaemonSetManaged Prometheus collector
Security scanningCustom agent DaemonSetGoogle Security Command Center
Network pluginCustom CNI DaemonSetKhông thể migrate → dùng Standard
bash
# Xem DaemonSets hiện tại
kubectl get daemonsets --all-namespaces

# Kiểm tra DaemonSet có phải managed không
kubectl get daemonset -n kube-system -o yaml | grep "google\|gke"

3. hostNetwork và host namespaces

Vấn đề:

yaml
# Bị block trong Autopilot
spec:
  hostNetwork: true
  hostPID: true
  hostIPC: true

Giải pháp: Refactor sang network-based communication:

yaml
# Thay hostNetwork bằng Service
apiVersion: v1
kind: Service
spec:
  type: ClusterIP
  ports:
  - port: 8080

Nếu workload dùng hostNetwork để access node-level network stack (ví dụ: monitoring network traffic), không thể migrate — đây là hard incompatibility.

4. HostPath volumes

Vấn đề:

yaml
# Bị block trừ /var/log read-only
volumes:
- name: host-data
  hostPath:
    path: /var/data
    type: Directory

Giải pháp:

  • Dùng PersistentVolumeClaim thay vì HostPath
  • Nếu cần shared data giữa containers trong cùng Pod: dùng emptyDir
  • Nếu cần read logs: chỉ allowed read-only /var/log
yaml
# Thay hostPath bằng PVC
volumes:
- name: data
  persistentVolumeClaim:
    claimName: my-pvc

5. Resource requests không hợp lệ

Vấn đề:

yaml
# Standard: Hoạt động (nhưng không recommend)
resources: {}  # Không có requests

# Hoặc ratio vi phạm
resources:
  requests:
    cpu: "100m"
    memory: "10Gi"  # Ratio 1:100, vi phạm

Giải pháp: Thêm resource requests đúng:

python
# Script để audit resource requests
#!/usr/bin/env python3
import subprocess
import json

result = subprocess.run(
    ['kubectl', 'get', 'pods', '--all-namespaces', '-o', 'json'],
    capture_output=True, text=True
)
pods = json.loads(result.stdout)

for pod in pods['items']:
    for container in pod['spec'].get('containers', []):
        resources = container.get('resources', {})
        requests = resources.get('requests', {})
        if not requests.get('cpu') or not requests.get('memory'):
            print(f"Missing requests: {pod['metadata']['namespace']}/{pod['metadata']['name']}/{container['name']}")

6. calico NetworkPolicies

Vấn đề:

yaml
# Calico-specific CRD, không hỗ trợ trong Autopilot
apiVersion: crd.projectcalico.org/v1
kind: GlobalNetworkPolicy

Giải pháp: Convert sang Kubernetes standard NetworkPolicy hoặc Cilium NetworkPolicy:

yaml
# Standard Kubernetes NetworkPolicy (hoạt động trong Autopilot)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: my-policy
spec:
  podSelector:
    matchLabels:
      app: my-app
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend

7. Custom Sysctl

Vấn đề:

yaml
# Không hỗ trợ trong Autopilot
spec:
  securityContext:
    sysctls:
    - name: net.core.somaxconn
      value: "1024"
    - name: net.ipv4.tcp_syn_retries
      value: "3"

Giải pháp: Không có direct workaround. Nếu workload thực sự cần sysctl tuning, không thể migrate. Alternatives:

  • Nhiều sysctl settings có thể compensate bằng application-level tuning (connection pooling, retry logic)
  • Kiểm tra xem sysctl có thực sự cần thiết ở current scale không

8. Routes-based networking

Vấn đề: Cluster dùng routes-based (không phải VPC-native) networking.

Không có in-place migration — phải tạo cluster mới với VPC-native và migrate workloads.

bash
# Kiểm tra loại networking
gcloud container clusters describe CLUSTER_NAME \
  --region REGION \
  --format="value(ipAllocationPolicy.useIpAliases)"
# "true" = VPC-native, empty = routes-based

Bước 3: Migration strategies

bash
# 1. Tạo Autopilot cluster mới
gcloud container clusters create-auto autopilot-prod \
  --region us-central1 \
  --release-channel regular \
  --network my-vpc \
  --subnetwork my-subnet

# 2. Setup kubectl contexts
gcloud container clusters get-credentials autopilot-prod --region us-central1
kubectl config rename-context gke_project_us-central1_autopilot-prod autopilot-prod

# 3. Deploy workloads vào Autopilot cluster
kubectl --context=autopilot-prod apply -f k8s/production/

# 4. Verify workloads healthy
kubectl --context=autopilot-prod get pods --all-namespaces
kubectl --context=autopilot-prod rollout status deployment/my-app -n production

# 5. Switch DNS/LB trỏ sang Autopilot cluster (traffic cutover)
# (Tùy thuộc vào cơ chế LB của bạn)

# 6. Monitor trong vài ngày
# 7. Decommission Standard cluster
gcloud container clusters delete standard-prod --region us-central1

Strategy B: Multi-Cluster Services (zero-downtime cho stateless)

Dùng MCS (Multi-Cluster Services) để route traffic song song trong quá trình migration:

yaml
# Export service từ Standard cluster
apiVersion: net.gke.io/v1
kind: ServiceExport
metadata:
  name: my-app
  namespace: production

# Import trong Autopilot cluster
apiVersion: net.gke.io/v1
kind: ServiceImport
metadata:
  name: my-app
  namespace: production

LB sẽ split traffic giữa hai clusters, cho phép canary migration.

Strategy C: Stateful workload migration (Backup for GKE)

bash
# 1. Enable Backup for GKE trên Standard cluster
gcloud container backup-restore backup-plans create standard-backup \
  --cluster=standard-prod \
  --location=us-central1 \
  --backup-retain-days=7

# 2. Tạo backup
gcloud container backup-restore backups create migration-backup \
  --backup-plan=standard-backup \
  --location=us-central1

# 3. Restore vào Autopilot cluster
gcloud container backup-restore restore-plans create restore-to-autopilot \
  --backup-plan=standard-backup \
  --cluster=autopilot-prod \
  --location=us-central1

gcloud container backup-restore restores create restore-migration \
  --restore-plan=restore-to-autopilot \
  --backup=migration-backup \
  --location=us-central1

Lưu ý: Cross-region stateful migration phải dùng Backup for GKE. Same-region có thể dùng manual disk reattachment.

Bước 4: Validate sau migration

bash
# Kiểm tra tất cả workloads running
kubectl get deployments,statefulsets,daemonsets --all-namespaces

# Kiểm tra resource adjustments đã xảy ra
kubectl get pods --all-namespaces -o json | \
  python3 -c "
import json, sys
pods = json.load(sys.stdin)
for pod in pods['items']:
    annotations = pod.get('metadata', {}).get('annotations', {})
    if 'autopilot.gke.io/resource-adjustment' in annotations:
        print(f\"{pod['metadata']['namespace']}/{pod['metadata']['name']}: {annotations['autopilot.gke.io/resource-adjustment']}\")
"

# Kiểm tra không có Pods pending vì resource issues
kubectl get pods --all-namespaces --field-selector=status.phase=Pending

# Verify billing model (xem cost allocation)
gcloud billing accounts list

Running Autopilot Pods trong Standard clusters

Từ GKE 1.31+, bạn có thể chạy Autopilot-style workloads trong Standard clusters bằng cách bật autopilotMode trong Custom ComputeClass. Đây hữu ích để:

  • Test Autopilot compatibility mà không cần cluster mới
  • Migration từng phần — một số workloads dùng Autopilot mode, phần còn lại Standard
yaml
# ComputeClass với Autopilot mode trong Standard cluster
apiVersion: cloud.google.com/v1
kind: ComputeClass
metadata:
  name: autopilot-compatible
spec:
  autopilotMode:
    enabled: true
  nodeConfigurations:
  - machineType: "e2-standard-4"
    nodePoolAutoCreation:
      enabled: true
yaml
# Pod dùng Autopilot mode trong Standard cluster
spec:
  nodeSelector:
    cloud.google.com/compute-class: "autopilot-compatible"
  containers:
  - name: app
    resources:
      requests:
        cpu: "500m"
        memory: "1Gi"

Hạn chế: Autopilot mode trong Standard cluster không có đầy đủ feature của true Autopilot cluster:

  • Security restrictions nhẹ hơn (do Standard cluster có thể cho phép privileged Pods trên nodes khác)
  • Billing vẫn là per-node cho Standard node pools
  • Maintenance handling khác nhau

Checklist trước khi bắt đầu migration

markdown
### Pre-migration checklist

**Assessment**
- [ ] Chạy `gcloud container clusters check-autopilot-compatibility`
- [ ] Review incompatibility report, phân loại hard vs soft incompatibilities
- [ ] Estimate chi phí Autopilot (so sánh với Standard hiện tại)
- [ ] Identify workloads cần thay đổi manifest

**Preparation**
- [ ] Cập nhật resource requests cho tất cả Pods (minimum đáp ứng Autopilot requirements)
- [ ] Remove/replace custom DaemonSets
- [ ] Convert Calico policies sang standard NetworkPolicy
- [ ] Remove hostNetwork, hostPID, hostIPC
- [ ] Restrict HostPath volumes chỉ còn /var/log read-only
- [ ] Remove privileged containers hoặc tìm alternative
- [ ] Remove custom sysctl settings
- [ ] Test tất cả changes trong staging environment

**Migration execution**
- [ ] Tạo Autopilot cluster (đúng region, VPC, CIDR sizing)
- [ ] Deploy workloads theo strategy phù hợp
- [ ] Verify tất cả workloads healthy trên Autopilot
- [ ] Monitor metrics và logs 24-48 giờ
- [ ] Kiểm tra resource adjustments không tạo ra cost surprise

**Cutover và cleanup**
- [ ] Switch traffic sang Autopilot cluster
- [ ] Monitor sau cutover
- [ ] Giữ Standard cluster standby ít nhất 1 tuần
- [ ] Decommission Standard cluster sau khi xác nhận ổn định

Common mistakes khi migrate

Mistake 1: Không estimate cost trước

Autopilot bill theo requested resources, không actual. Nếu workloads có requests quá cao (over-provisioned), bill Autopilot sẽ cao hơn Standard vì Standard chạy nhiều workloads trên cùng node với unused capacity.

Fix: Dùng VPA recommendation để optimize requests trước khi migrate.

Mistake 2: Migrate stateful workloads cùng lúc stateless

Stateful workloads (databases, queues) cần cẩn thận hơn nhiều về data consistency và downtime. Nên migrate stateless trước để validate process, rồi mới đến stateful.

Mistake 3: Không test trong staging Autopilot cluster

Security restrictions trong Autopilot có thể break workloads theo những cách không ngờ tới. Luôn test trong staging Autopilot cluster trước khi migrate production.

Mistake 4: Không cập nhật monitoring và alerting

Một số metrics và log paths thay đổi giữa Standard và Autopilot. Alert based on node metrics sẽ không hoạt động trong Autopilot. Phải update dashboards và alerting rules.

References