Google Cloud Tutorial · Compute · Lesson 11 of 27
Compute Engine and Managed Instance Groups
Virtual machines on Google Cloud: machine families, disks, Spot VMs, and managed instance groups for autoscaling and self-healing.
Virtual machines
A Compute Engine VM has a machine type (general purpose E2, N2, N4, C4; compute-optimised; memory-optimised; accelerator-optimised with GPUs), a boot image, attached persistent disks or Hyperdisks, a network interface in a subnet, and an attached service account.
gcloud compute instances create web-1 --zone europe-west1-b \
--machine-type e2-standard-2 --image-family debian-12 --image-project debian-cloud \
--service-account [email protected] --no-address
Spot VMs are much cheaper but can be stopped whenever Google needs the capacity; use them for work that can restart.
Managed instance groups (MIGs)
A MIG creates identical VMs from an instance template and:
- autoscales on CPU, load balancer utilisation or custom metrics;
- autoheals: recreates VMs that fail an application health check;
- rolls out a new template gradually, with surge and unavailable limits;
- when regional, spreads VMs across zones.
import math
target_cpu = 0.6 # keep average CPU around 60%
min_vms, max_vms = 2, 10
vms = 2
for minute, total_cpu_needed in enumerate([0.8, 1.5, 3.2, 4.8, 4.0, 2.0, 0.9]):
# total_cpu_needed: how many VMs' worth of CPU the traffic needs
wanted = math.ceil(total_cpu_needed / target_cpu)
vms = max(min_vms, min(max_vms, wanted))
print(f"minute {minute}: load {total_cpu_needed:.1f} VMs of CPU -> run {vms} VMs "
f"(avg CPU {total_cpu_needed / vms:.0%})")
Output
minute 0: load 0.8 VMs of CPU -> run 2 VMs (avg CPU 40%) minute 1: load 1.5 VMs of CPU -> run 3 VMs (avg CPU 50%) minute 2: load 3.2 VMs of CPU -> run 6 VMs (avg CPU 53%) minute 3: load 4.8 VMs of CPU -> run 8 VMs (avg CPU 60%) minute 4: load 4.0 VMs of CPU -> run 7 VMs (avg CPU 57%) minute 5: load 2.0 VMs of CPU -> run 4 VMs (avg CPU 50%) minute 6: load 0.9 VMs of CPU -> run 2 VMs (avg CPU 45%)
Test yourself
What does autohealing in a managed instance group do?
Patches the operating systemRecreates VMs whose application health check failsMoves VMs to cheaper regionsBacks up disks
Show answer
Answer: Recreates VMs whose application health check fails
Autohealing replaces unhealthy instances based on a health check.