VMs are the most flexible compute option and the base layer under GKE and many managed services.
Compute Engine runs virtual machines in a zone. When creating one you choose:
- Machine type: family plus size, e.g.
e2-medium(cost-optimised, shared-core options),n4-standard-4(general purpose),c4-(compute-optimised),t2d-/t2a-(scale-out, Arm in t2a). Custom shapes are possible on some families. - Boot image: public images from projects like
debian-cloudorubuntu-os-cloud, chosen by image family to get the latest version. - Disks: a boot disk plus optional Persistent Disk or Hyperdisk volumes; they outlive the VM unless set to auto-delete.
- Service account and scopes, network and subnet, and whether it gets an external IP.
Connect with gcloud compute ssh, which creates and propagates SSH keys for you (or uses OS Login when enabled). With --tunnel-through-iap you can reach VMs that have no external IP.
Startup scripts (metadata key startup-script) run at every boot; good for simple setup. A stopped VM stops compute billing, but its disks and reserved static IPs are still charged.
Spot VMs (--provisioning-model=SPOT) cost much less but can be preempted at any time with 30 seconds' notice: great for batch jobs and fault-tolerant workers, never for a single stateful server.
Example
gcloud compute instances create web-1 \
--zone=europe-west1-b --machine-type=e2-medium \
--image-family=debian-12 --image-project=debian-cloud \
--tags=http-server --metadata=startup-script='#!/bin/bash
apt-get update && apt-get install -y nginx'
gcloud compute instances list --format="table(name,zone.basename(),status,networkInterfaces[0].accessConfigs[0].natIP)"
# NAME ZONE STATUS NAT_IP
# web-1 europe-west1-b RUNNING 34.76.12.34
gcloud compute ssh web-1 --zone=europe-west1-b # keys handled for you
gcloud compute instances stop web-1 --zone=europe-west1-bRemember
- Pick machine family by workload; e2 is the cheap default
- Use image families to always get the latest patched image
- Stopped VMs still pay for disks and static IPs
- Spot VMs are cheap but preemptible
Watch out for
- Running a database on a Spot VM, or on a VM with a local SSD only, and losing data when it goes away.