gcp-compute

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GCP Compute Engine

GCP Compute Engine

Deploy, manage, and scale Compute Engine virtual machines on Google Cloud Platform.
在Google Cloud Platform上部署、管理和扩展Compute Engine虚拟机。

When to Use

使用场景

  • Deploying web servers, application backends, or batch-processing workloads on GCP
  • Running workloads that need full OS-level control (unlike Cloud Run or App Engine)
  • Creating managed instance groups for auto-healing and auto-scaling behind a load balancer
  • Provisioning GPU-attached VMs for ML training or rendering pipelines
  • Cost-optimizing non-critical workloads with preemptible or spot VMs
  • 在GCP上部署Web服务器、应用后端或批处理工作负载
  • 运行需要完整操作系统级控制的工作负载(不同于Cloud Run或App Engine)
  • 创建托管实例组,在负载均衡器后方实现自动修复和自动扩缩容
  • 配置搭载GPU的VM用于机器学习训练或渲染流水线
  • 使用抢占式或Spot VM优化非关键工作负载的成本

Prerequisites

前置条件

  • Google Cloud SDK (
    gcloud
    ) installed and authenticated
  • A GCP project with the Compute Engine API enabled
  • IAM role
    roles/compute.admin
    or scoped roles for instance management
bash
gcloud auth list
gcloud config set project $PROJECT_ID
gcloud services enable compute.googleapis.com
  • 已安装并完成认证的Google Cloud SDK(
    gcloud
  • 已启用Compute Engine API的GCP项目
  • 具备
    roles/compute.admin
    权限或实例管理的细分IAM角色
bash
gcloud auth list
gcloud config set project $PROJECT_ID
gcloud services enable compute.googleapis.com

Machine Types Reference

机器类型参考

FamilyExamplevCPUsMemoryUse Case
E2e2-micro0.251 GBDev/test, microservices
E2e2-medium14 GBLight web servers
N2n2-standard-4416 GBGeneral-purpose production
N2n2-highmem-8864 GBIn-memory caches, databases
C2c2-standard-161664 GBCompute-intensive, HPC
bash
undefined
系列示例vCPU数内存使用场景
E2e2-micro0.251 GB开发/测试、微服务
E2e2-medium14 GB轻量Web服务器
N2n2-standard-4416 GB通用生产环境
N2n2-highmem-8864 GB内存缓存、数据库
C2c2-standard-161664 GB计算密集型、高性能计算
bash
undefined

List machine types available in a zone

列出可用区中的机器类型

gcloud compute machine-types list --zones=us-central1-a --filter="name~'e2-'"
gcloud compute machine-types list --zones=us-central1-a --filter="name~'e2-'"

Create a custom machine type (6 vCPUs, 24 GB RAM)

创建自定义机器类型(6核CPU,24GB内存)

gcloud compute instances create custom-vm
--custom-cpu=6 --custom-memory=24GB
--zone=us-central1-a
--image-family=debian-12 --image-project=debian-cloud
undefined
gcloud compute instances create custom-vm
--custom-cpu=6 --custom-memory=24GB
--zone=us-central1-a
--image-family=debian-12 --image-project=debian-cloud
undefined

Create an Instance

创建实例

bash
undefined
bash
undefined

Production instance with shielded VM and startup script

带防护型VM和启动脚本的生产环境实例

gcloud compute instances create web-server
--machine-type=e2-medium
--zone=us-central1-a
--image-family=debian-12
--image-project=debian-cloud
--boot-disk-size=20GB
--boot-disk-type=pd-balanced
--tags=http-server,https-server
--labels=env=production,team=backend
--metadata=enable-oslogin=TRUE
--shielded-secure-boot
--shielded-vtpm
--shielded-integrity-monitoring
gcloud compute instances create web-server
--machine-type=e2-medium
--zone=us-central1-a
--image-family=debian-12
--image-project=debian-cloud
--boot-disk-size=20GB
--boot-disk-type=pd-balanced
--tags=http-server,https-server
--labels=env=production,team=backend
--metadata=enable-oslogin=TRUE
--shielded-secure-boot
--shielded-vtpm
--shielded-integrity-monitoring

Instance with a startup script and service account

带启动脚本和服务账号的实例

gcloud compute instances create app-server
--machine-type=e2-standard-2
--zone=us-central1-a
--image-family=ubuntu-2204-lts
--image-project=ubuntu-os-cloud
--boot-disk-size=50GB
--metadata-from-file=startup-script=startup.sh
--service-account=app-sa@${PROJECT_ID}.iam.gserviceaccount.com
--scopes=cloud-platform
gcloud compute instances create app-server
--machine-type=e2-standard-2
--zone=us-central1-a
--image-family=ubuntu-2204-lts
--image-project=ubuntu-os-cloud
--boot-disk-size=50GB
--metadata-from-file=startup-script=startup.sh
--service-account=app-sa@${PROJECT_ID}.iam.gserviceaccount.com
--scopes=cloud-platform

Instance with an additional data disk

带附加数据盘的实例

gcloud compute instances create db-server
--machine-type=n2-highmem-4
--zone=us-central1-a
--image-family=debian-12 --image-project=debian-cloud
--boot-disk-size=20GB
--create-disk=name=data-disk,size=200GB,type=pd-ssd,auto-delete=no
undefined
gcloud compute instances create db-server
--machine-type=n2-highmem-4
--zone=us-central1-a
--image-family=debian-12 --image-project=debian-cloud
--boot-disk-size=20GB
--create-disk=name=data-disk,size=200GB,type=pd-ssd,auto-delete=no
undefined

Startup Script Example

启动脚本示例

bash
#!/bin/bash
bash
#!/bin/bash

startup.sh - runs on first boot and every reboot

startup.sh - 在首次启动和每次重启时运行

set -euo pipefail apt-get update && apt-get install -y nginx systemctl enable nginx && systemctl start nginx curl -X PUT -H "Metadata-Flavor: Google"
"http://metadata.google.internal/computeMetadata/v1/instance/guest-attributes/startup/status"
-d "complete"
undefined
set -euo pipefail apt-get update && apt-get install -y nginx systemctl enable nginx && systemctl start nginx curl -X PUT -H "Metadata-Flavor: Google"
"http://metadata.google.internal/computeMetadata/v1/instance/guest-attributes/startup/status"
-d "complete"
undefined

Instance Templates and Managed Instance Groups

实例模板与托管实例组

bash
undefined
bash
undefined

Create an instance template

创建实例模板

gcloud compute instance-templates create web-template
--machine-type=e2-medium
--image-family=debian-12 --image-project=debian-cloud
--boot-disk-size=20GB --tags=http-server
--metadata-from-file=startup-script=startup.sh
gcloud compute instance-templates create web-template
--machine-type=e2-medium
--image-family=debian-12 --image-project=debian-cloud
--boot-disk-size=20GB --tags=http-server
--metadata-from-file=startup-script=startup.sh

Create a regional managed instance group (MIG) with health check

创建带健康检查的区域托管实例组(MIG)

gcloud compute health-checks create http http-health-check
--port=80 --request-path=/healthz
--check-interval=10s --timeout=5s
--healthy-threshold=2 --unhealthy-threshold=3
gcloud compute instance-groups managed create web-mig
--template=web-template --size=3
--region=us-central1
--health-check=http-health-check --initial-delay=120
gcloud compute health-checks create http http-health-check
--port=80 --request-path=/healthz
--check-interval=10s --timeout=5s
--healthy-threshold=2 --unhealthy-threshold=3
gcloud compute instance-groups managed create web-mig
--template=web-template --size=3
--region=us-central1
--health-check=http-health-check --initial-delay=120

Configure autoscaling

配置自动扩缩容

gcloud compute instance-groups managed set-autoscaling web-mig
--region=us-central1
--min-num-replicas=2 --max-num-replicas=10
--target-cpu-utilization=0.65 --cool-down-period=90
gcloud compute instance-groups managed set-autoscaling web-mig
--region=us-central1
--min-num-replicas=2 --max-num-replicas=10
--target-cpu-utilization=0.65 --cool-down-period=90

Rolling update to a new template

滚动更新至新模板

gcloud compute instance-groups managed rolling-action start-update web-mig
--version=template=web-template-v2
--region=us-central1 --max-surge=3 --max-unavailable=0
undefined
gcloud compute instance-groups managed rolling-action start-update web-mig
--version=template=web-template-v2
--region=us-central1 --max-surge=3 --max-unavailable=0
undefined

Preemptible and Spot VMs

抢占式与Spot VM

bash
undefined
bash
undefined

Spot VM (recommended over legacy preemptible)

Spot VM(推荐替代传统抢占式VM)

gcloud compute instances create spot-worker
--machine-type=n2-standard-8
--zone=us-central1-a
--image-family=debian-12 --image-project=debian-cloud
--provisioning-model=SPOT
--instance-termination-action=STOP
gcloud compute instances create spot-worker
--machine-type=n2-standard-8
--zone=us-central1-a
--image-family=debian-12 --image-project=debian-cloud
--provisioning-model=SPOT
--instance-termination-action=STOP

Spot instance template for batch MIG

用于批处理MIG的Spot实例模板

gcloud compute instance-templates create batch-template
--machine-type=n2-standard-4
--image-family=debian-12 --image-project=debian-cloud
--provisioning-model=SPOT
--instance-termination-action=DELETE
undefined
gcloud compute instance-templates create batch-template
--machine-type=n2-standard-4
--image-family=debian-12 --image-project=debian-cloud
--provisioning-model=SPOT
--instance-termination-action=DELETE
undefined

Snapshots and Images

快照与镜像

bash
undefined
bash
undefined

Create a snapshot

创建快照

gcloud compute disks snapshot web-server
--zone=us-central1-a
--snapshot-names=web-server-snap-$(date +%Y%m%d)
gcloud compute disks snapshot web-server
--zone=us-central1-a
--snapshot-names=web-server-snap-$(date +%Y%m%d)

Scheduled snapshot policy

定时快照策略

gcloud compute resource-policies create snapshot-schedule daily-backup
--region=us-central1 --max-retention-days=14
--daily-schedule --start-time=03:00
gcloud compute disks add-resource-policies web-server
--zone=us-central1-a --resource-policies=daily-backup
gcloud compute resource-policies create snapshot-schedule daily-backup
--region=us-central1 --max-retention-days=14
--daily-schedule --start-time=03:00
gcloud compute disks add-resource-policies web-server
--zone=us-central1-a --resource-policies=daily-backup

Create a custom image from an instance

从实例创建自定义镜像

gcloud compute instances stop web-server --zone=us-central1-a gcloud compute images create web-golden-image
--source-disk=web-server --source-disk-zone=us-central1-a
--family=web-server --labels=version=v1
undefined
gcloud compute instances stop web-server --zone=us-central1-a gcloud compute images create web-golden-image
--source-disk=web-server --source-disk-zone=us-central1-a
--family=web-server --labels=version=v1
undefined

Terraform Configuration

Terraform配置

hcl
resource "google_compute_instance" "web" {
  name         = "web-server"
  machine_type = "e2-medium"
  zone         = "us-central1-a"
  tags         = ["http-server", "https-server"]

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-12"
      size  = 20
      type  = "pd-balanced"
    }
  }

  network_interface {
    subnetwork = google_compute_subnetwork.main.id
    access_config {}
  }

  metadata_startup_script = file("${path.module}/startup.sh")

  service_account {
    email  = google_service_account.app.email
    scopes = ["cloud-platform"]
  }

  shielded_instance_config {
    enable_secure_boot          = true
    enable_vtpm                 = true
    enable_integrity_monitoring = true
  }
}

resource "google_compute_instance_template" "web" {
  name_prefix  = "web-"
  machine_type = "e2-medium"

  disk {
    source_image = "debian-cloud/debian-12"
    auto_delete  = true
    boot         = true
    disk_size_gb = 20
  }

  network_interface {
    subnetwork = google_compute_subnetwork.main.id
  }

  lifecycle { create_before_destroy = true }
}

resource "google_compute_region_instance_group_manager" "web" {
  name               = "web-mig"
  base_instance_name = "web"
  region             = "us-central1"

  version {
    instance_template = google_compute_instance_template.web.id
  }

  target_size = 3
  named_port { name = "http"; port = 80 }

  auto_healing_policies {
    health_check      = google_compute_health_check.http.id
    initial_delay_sec = 120
  }
}

resource "google_compute_region_autoscaler" "web" {
  name   = "web-autoscaler"
  region = "us-central1"
  target = google_compute_region_instance_group_manager.web.id

  autoscaling_policy {
    min_replicas    = 2
    max_replicas    = 10
    cooldown_period = 90
    cpu_utilization { target = 0.65 }
  }
}
hcl
resource "google_compute_instance" "web" {
  name         = "web-server"
  machine_type = "e2-medium"
  zone         = "us-central1-a"
  tags         = ["http-server", "https-server"]

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-12"
      size  = 20
      type  = "pd-balanced"
    }
  }

  network_interface {
    subnetwork = google_compute_subnetwork.main.id
    access_config {}
  }

  metadata_startup_script = file("${path.module}/startup.sh")

  service_account {
    email  = google_service_account.app.email
    scopes = ["cloud-platform"]
  }

  shielded_instance_config {
    enable_secure_boot          = true
    enable_vtpm                 = true
    enable_integrity_monitoring = true
  }
}

resource "google_compute_instance_template" "web" {
  name_prefix  = "web-"
  machine_type = "e2-medium"

  disk {
    source_image = "debian-cloud/debian-12"
    auto_delete  = true
    boot         = true
    disk_size_gb = 20
  }

  network_interface {
    subnetwork = google_compute_subnetwork.main.id
  }

  lifecycle { create_before_destroy = true }
}

resource "google_compute_region_instance_group_manager" "web" {
  name               = "web-mig"
  base_instance_name = "web"
  region             = "us-central1"

  version {
    instance_template = google_compute_instance_template.web.id
  }

  target_size = 3
  named_port { name = "http"; port = 80 }

  auto_healing_policies {
    health_check      = google_compute_health_check.http.id
    initial_delay_sec = 120
  }
}

resource "google_compute_region_autoscaler" "web" {
  name   = "web-autoscaler"
  region = "us-central1"
  target = google_compute_region_instance_group_manager.web.id

  autoscaling_policy {
    min_replicas    = 2
    max_replicas    = 10
    cooldown_period = 90
    cpu_utilization { target = 0.65 }
  }
}

Common Operations

常见操作

bash
undefined
bash
undefined

SSH into an instance

SSH登录实例

gcloud compute ssh web-server --zone=us-central1-a
gcloud compute ssh web-server --zone=us-central1-a

List all instances with status

列出所有实例及状态

gcloud compute instances list
--format="table(name,zone,status,machineType.basename())"
gcloud compute instances list
--format="table(name,zone,status,machineType.basename())"

Stop / start / resize

停止/启动/调整实例规格

gcloud compute instances stop web-server --zone=us-central1-a gcloud compute instances set-machine-type web-server
--machine-type=e2-standard-4 --zone=us-central1-a gcloud compute instances start web-server --zone=us-central1-a
gcloud compute instances stop web-server --zone=us-central1-a gcloud compute instances set-machine-type web-server
--machine-type=e2-standard-4 --zone=us-central1-a gcloud compute instances start web-server --zone=us-central1-a

View serial port output (debug startup scripts)

查看串口输出(调试启动脚本)

gcloud compute instances get-serial-port-output web-server --zone=us-central1-a
undefined
gcloud compute instances get-serial-port-output web-server --zone=us-central1-a
undefined

Troubleshooting

故障排查

SymptomCauseFix
Instance stuck in STAGINGQuota exceeded or resource unavailableCheck quota with
gcloud compute project-info describe
; try another zone
Startup script not runningSyntax errors or wrong metadata keyCheck serial output; ensure key is
startup-script
not
startup_script
Cannot SSHFirewall blocks port 22 or OS Login misconfiguredAdd firewall rule for
tcp:22
; verify
enable-oslogin
metadata
Preempted too oftenZone resource pressureUse Spot VM with
STOP
action; spread across zones in a MIG
Disk out of spaceBoot disk too smallUse
gcloud compute disks resize
; enable
--storage-auto-increase
for data disks
MIG not healingHealth check misconfigured or initial delay too shortVerify health check path returns 200; increase
--initial-delay
症状原因解决方法
实例卡在STAGING状态配额不足或资源不可用使用
gcloud compute project-info describe
检查配额;尝试其他可用区
启动脚本未运行语法错误或元数据键错误检查串口输出;确保键为
startup-script
而非
startup_script
无法SSH登录防火墙阻止22端口或OS Login配置错误添加
tcp:22
的防火墙规则;验证
enable-oslogin
元数据
抢占过于频繁可用区资源紧张使用带
STOP
动作的Spot VM;在MIG中跨可用区分布实例
磁盘空间不足启动盘过小使用
gcloud compute disks resize
扩容;为数据盘启用
--storage-auto-increase
MIG未自动修复健康检查配置错误或初始延迟过短验证健康检查路径返回200;增加
--initial-delay
时长

Related Skills

相关技能

  • gcp-networking - VPC, firewall rules, and load balancers for Compute Engine
  • terraform-gcp - Provision Compute Engine resources with Infrastructure as Code
  • gcp-gke - When workloads are better suited for containers than VMs
  • gcp-cloud-sql - Managed databases that Compute Engine applications connect to
  • gcp-networking - 用于Compute Engine的VPC、防火墙规则和负载均衡器
  • terraform-gcp - 使用基础设施即代码(IaC)配置Compute Engine资源
  • gcp-gke - 当工作负载更适合容器而非VM时使用
  • gcp-cloud-sql - Compute Engine应用连接的托管数据库