How do I automatically restart a GCE preemptible instance?

You could create a f1-micro instance which is free for one instance per month in several data centers and create a cron job

*/10 * * * * /snap/bin/gcloud beta compute instances start --zone "yourzone" "yourinstance" --project "yourproject"

after you ran gcloud auth login once.

This will restart your instance every 10 minutes. Of course you can set this also to an hour or more. With a bit more scripting also things like exponential back off can be done.


You could try using Instance Group Manager to set up a pool of size 1. It will then try to re-create instances after they are preempted.

You should be aware that there is no guarantee that there is going to be capacity for your instance. As the docs say:

Preemptible instances are available from a finite amount of Compute Engine resources, and might not always be available.