Overview and What You Will Learn
A Managed Instance Group (MIG) runs a fleet of identical VMs created from one instance template and manages them as a single unit. It is the Google Cloud equivalent of an AWS Auto Scaling group or an Azure VM Scale Set. Add an autoscaler and the group grows and shrinks with load, and add autohealing and it replaces VMs that stop responding.
In this lab you will:
- Create an instance template with a startup script
- Build a MIG from it and wait for it to become stable
- Configure CPU-based autoscaling with sensible bounds and a cool-down period
- Add autohealing with a health check
- Generate load, watch the group scale out, and read the autoscaler's decisions
- Roll out a new template version with a rolling update
Why This Matters in Production
During a flash sale, an e-commerce app can see traffic jump many times over in minutes. Launching VMs by hand at 2 AM is slow and error-prone, and keeping peak capacity running all year is wasteful. A platform team at a company like Swiggy or Shopify uses a MIG with autoscaling so capacity follows demand and unhealthy VMs are replaced without a page.
Core Principles
The instance template says what a VM looks like, the MIG keeps the requested number of VMs running from it, and the autoscaler changes that number based on a signal such as average CPU utilization.
machine type, image, script] --> M[Managed instance group] M --> V1([VM 1]) M --> V2([VM 2]) A[Autoscaler
CPU target and min/max] -->|sets size| M H[Health check] -->|recreates unhealthy| M classDef cfg fill:#DBEAFE,color:#1E293B classDef grp fill:#326CE5,color:#FFFFFF classDef vm fill:#10B981,color:#FFFFFF class T,A,H cfg class M grp class V1,V2 vm
Two details about the autoscaler are worth knowing before you start. It scales on the average utilization across the whole group, so load on only one VM may not trigger scaling. It also ignores a new VM's metrics during the cool-down period, so startup CPU spikes do not cause extra scale-outs.
| Group type | Behavior |
|---|---|
| Zonal MIG | All VMs in one zone, simpler, no protection from a zone outage |
| Regional MIG | VMs spread across zones in a region, survives a zone failure |
Detailed Step-by-Step Practical Lab
Milestone 1: Create the Project and an Instance Template
The startup script installs stress-ng, which you will use later to generate CPU load. Instance templates are immutable once created.
export PROJECT_ID=mig-lab-$(date +%s | tail -c 6)export ZONE=asia-south1-a gcloud projects create $PROJECT_ID --name="MIG Lab"gcloud config set project $PROJECT_IDgcloud billing projects link $PROJECT_ID --billing-account=0A1B2C-3D4E5F-6A7B8Cgcloud services enable compute.googleapis.com gcloud compute instance-templates create web-server-template-v1 \ --machine-type=e2-medium \ --image-family=debian-12 \ --image-project=debian-cloud \ --tags=web \ --metadata=startup-script='#! /bin/bashapt-get updateapt-get install -y nginx stress-ngecho "template v1 on $(hostname)" > /var/www/html/index.html'Milestone 2: Create the Managed Instance Group
Start with two instances and wait until every VM is running and passing its checks.
gcloud compute instance-groups managed create web-server-mig \ --template=web-server-template-v1 \ --size=2 \ --zone=$ZONE gcloud compute instance-groups managed wait-until web-server-mig \ --stable --zone=$ZONE gcloud compute instance-groups managed list-instances web-server-mig \ --zone=$ZONEMilestone 3: Configure Autoscaling
Set a minimum, a maximum and a target. A target of 0.7 means the autoscaler adds VMs when average CPU across the group stays above 70 percent.
gcloud compute instance-groups managed set-autoscaling web-server-mig \ --zone=$ZONE \ --min-num-replicas=2 \ --max-num-replicas=10 \ --target-cpu-utilization=0.7 \ --cool-down-period=90 gcloud compute autoscalers describe web-server-mig --zone=$ZONEThe cool-down period tells the autoscaler how long a new VM takes to become useful. Set it to at least the real startup time of your application, otherwise startup CPU can trigger an unnecessary scale-out.
Milestone 4: Add Autohealing
Autohealing recreates a VM that fails an application-level health check, which is different from autoscaling. The initial delay gives each VM time to boot before the checks count against it.
gcloud compute health-checks create http hc-web --port=80 --request-path=/ gcloud compute firewall-rules create allow-health-checks \ --network=default \ --direction=INGRESS \ --allow=tcp:80 \ --source-ranges=130.211.0.0/22,35.191.0.0/16 \ --target-tags=web gcloud compute instance-groups managed update web-server-mig \ --zone=$ZONE \ --health-check=hc-web \ --initial-delay=120Milestone 5: Generate Load and Watch the Group Scale
Because the autoscaler uses the group average, put load on every VM. This starts a CPU stress test in the background on each instance for 15 minutes.
for vm in $(gcloud compute instance-groups managed list-instances web-server-mig \ --zone=$ZONE --format='value(name)'); do gcloud compute ssh $vm --zone=$ZONE \ --command='sudo systemd-run --quiet stress-ng --cpu 0 --timeout 900s'done # Check every minute or two. New instances appear after several minuteswatch -n 60 "gcloud compute instance-groups managed list-instances web-server-mig --zone=$ZONE"Milestone 6: Read the Autoscaler's Decisions
Use the autoscaler resource and logs to see why the group changed size. Listing operations shows VM creation but not the reasoning.
# Current recommendation and statusgcloud compute autoscalers describe web-server-mig --zone=$ZONE \ --format="yaml(status, statusDetails, recommendedSize)" # Recent instance creations driven by the autoscalergcloud compute operations list \ --filter="operationType=compute.instances.insert AND targetLink~web-server-mig" \ --sort-by=~insertTime --limit=10When the stress test ends, the group scales back in toward the minimum. Scale-in is deliberately slower than scale-out, so expect it to take several more minutes.
Milestone 7: Roll Out a New Template with a Rolling Update
Templates cannot be edited, so you change the configuration by creating a new version and rolling it out gradually.
gcloud compute instance-templates create web-server-template-v2 \ --machine-type=e2-medium \ --image-family=debian-12 \ --image-project=debian-cloud \ --tags=web \ --metadata=startup-script='#! /bin/bashapt-get updateapt-get install -y nginx stress-ngecho "template v2 on $(hostname)" > /var/www/html/index.html' gcloud compute instance-groups managed rolling-action start-update web-server-mig \ --zone=$ZONE \ --version=template=web-server-template-v2 \ --max-surge=1 \ --max-unavailable=0 gcloud compute instance-groups managed wait-until web-server-mig \ --version-target-reached --zone=$ZONEWith --max-unavailable=0 and --max-surge=1, Google creates one new VM, waits for it to be healthy, then removes an old one, so capacity never drops during the rollout.
Milestone 8: Clean Up
gcloud projects delete $PROJECT_ID --quietProduction Best Practices & Common Pitfalls
- Pair autoscaling with autohealing. Scaling handles load, healing handles broken instances.
- Set the minimum for resilience, not cost. At least two instances, spread across zones with a regional MIG for production.
- Tune the cool-down to real startup time. Measure how long your app takes to serve traffic.
- Bake images for slow startups. Heavy startup scripts delay scale-out, so use custom images for large installs.
- Roll out with surge, not downtime. Use
--max-unavailable=0for user-facing services. - Put a load balancer in front. A MIG scales instances, a load balancer spreads traffic across them.
- Cap the maximum. An upper bound protects you from runaway cost when a bug drives CPU.
Common MistakeSetting the cool-down period shorter than the application's real startup time. The autoscaler then reads boot-time CPU as sustained load and adds more VMs than needed.
TipScale on a metric that matches the bottleneck. CPU suits compute-bound apps, but a load balancer utilization or custom metric often tracks web traffic better.
RememberAutoscaling averages across the group, so a single hot VM will not trigger a scale-out.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
gcloud compute instance-templates create |
Define a reusable VM configuration |
gcloud compute instance-groups managed create |
Create a MIG from a template |
gcloud compute instance-groups managed set-autoscaling |
Configure autoscaling |
gcloud compute instance-groups managed list-instances |
List instances and their status |
gcloud compute instance-groups managed rolling-action start-update |
Roll out a new template |
gcloud compute autoscalers describe |
Show autoscaler status |
| Symptom | Likely cause and fix |
|---|---|
| Group never scales out | Load only on some VMs, or target too high, check average CPU |
| Instances recreated in a loop | Health check failing, check the firewall rule, port and initial delay |
| Scale-out too aggressive | Cool-down too short, set it to the real startup time |
| Scale-in is slow | Expected, scale-in is intentionally gradual |
| Rolling update stalls | New template VMs fail health checks, test the template on one VM first |