Single VMs are pets; MIGs give you self-healing, scalable fleets that load balancers can target.
An instance template is an immutable description of a VM: machine type, image, disks, metadata, tags, service account. A managed instance group (MIG) creates and maintains N identical VMs from a template.
What a MIG does for you:
- Autoscaling on CPU utilisation, load balancer serving capacity, Cloud Monitoring metrics or schedules, between a min and max size.
- Autohealing: with a health check attached, unhealthy VMs are recreated. Set an initial delay long enough for boot and app start.
- Regional MIGs spread VMs across zones of a region, so a zone outage does not take the service down. Prefer them over zonal MIGs for serving.
- Rolling updates: point the group at a new template and it replaces VMs gradually, controlled by
--max-surgeand--max-unavailable. Canary by updating only a fraction of instances.
Because templates are immutable, a change means a new template (web-tpl-v2) and a rolling update. VMs in a MIG should be stateless and configured at boot (startup script, baked image or containers) since any of them can be deleted and recreated at any time.
MIGs are the classic backend for a load balancer. Unmanaged instance groups exist too, but only group existing VMs and offer none of the above.
Example
gcloud compute instance-templates create web-tpl-v1 \
--machine-type=e2-small --image-family=debian-12 --image-project=debian-cloud \
--tags=http-server --metadata-from-file=startup-script=startup.sh
gcloud compute health-checks create http web-hc --port=80 --request-path=/healthz
gcloud compute instance-groups managed create web-mig --region=europe-west1 \
--template=web-tpl-v1 --size=2 --health-check=web-hc --initial-delay=120
gcloud compute instance-groups managed set-autoscaling web-mig --region=europe-west1 \
--min-num-replicas=2 --max-num-replicas=10 --target-cpu-utilization=0.6
# Later: roll out a new template with no capacity loss
gcloud compute instance-groups managed rolling-action start-update web-mig \
--region=europe-west1 --version=template=web-tpl-v2 --max-surge=3 --max-unavailable=0Remember
- Templates are immutable; change = new template + rolling update
- Regional MIGs survive a zone outage
- Autohealing needs a health check and a sensible initial delay
Watch out for
- Setting the autohealing initial delay shorter than boot time, so VMs are recreated in an endless loop.