
Compute EngineAuthorCloudBrum editorial teamLast reviewedReading time~12 minLevelBeginner to advanced
Google Compute Engine · Compute · Virtual machines (IaaS)
Rent virtual machines on Google’s infrastructure and shape the machine to fit: you control the operating system, disks and network, and can even set the exact vCPU and memory. Reach for it when Cloud Run, GKE or App Engine are too restrictive.
On this page (17 sections)
Mind map: Compute Engine at a glance
Free to share. The downloaded image includes the CloudBrum link.
Key features (summary)
- Many machine familiesGeneral-purpose, compute-optimised, memory-optimised and storage-optimised families, plus accelerator types for GPUs.
- Custom machine typesOn supported families you choose the exact number of vCPUs and amount of memory rather than a preset size.
- Images and image familiesBoot from public images, Marketplace images or your own, and use a family name to always get the newest version.
- Block storage choicesPersistent Disk and Hyperdisk for durable data, and Local SSD for very fast scratch space.
- Managed instance groupsRun a fleet of identical VMs that autoscale, heal themselves and update in rolling fashion behind Cloud Load Balancing.
- Live migrationWhen Google services a host, most VMs are moved to another one while they keep running, so planned maintenance seldom causes a restart.
- Shielded and Confidential VMsSecure boot, a virtual TPM and integrity monitoring, with Confidential VMs to keep data encrypted while it is processed.
- Per-second pricingBilling runs by the second after a one-minute minimum, with sustained and committed use discounts on top.
Basic concepts
- Instance (VM)
- A single virtual machine, billed for its vCPU and memory while it runs.
- Machine type
- The CPU and memory shape of a VM, such as e2-medium or n2-standard-4. Some families also accept a custom shape.
- Image and image family
- An image holds an operating system for a boot disk. A family is a pointer that always resolves to the latest image in a series.
- Project
- The unit that owns resources, billing and permissions. Every VM, disk and network sits inside exactly one project.
- Region and zone
- Regions are named geographies such as asia-south1; each one holds several zones, which are separate failure domains. A single VM is placed in exactly one zone.
- VPC network and subnet
- Your private network. A VPC network spans the world, while each subnet belongs to one region and defines the IP range for VMs there.
- Firewall rule
- A stateful allow or deny rule with a priority, applied to VMs through network tags or service accounts.
- Persistent Disk and Hyperdisk
- Durable network-attached storage that outlives the VM. The boot disk is created with the VM; data disks are optional extras.
- Service account
- The identity a VM uses when it calls Google Cloud APIs, which removes the need to store keys on the machine.
- Metadata and startup script
- Key-value settings attached to a VM, including a startup-script that runs on every boot. Both are visible to code running on the VM, so credentials belong in neither.
- Metadata server
- A local address (metadata.google.internal) from which a VM reads details about itself and obtains access tokens.
How to create & configure it
Launch a VM from the Google Cloud console
- Open Compute Engine and pick the projectIn the Google Cloud console choose the project from the top bar, then open Compute Engine → VM instances. Enable the Compute Engine API if prompted.
- Name the instance and add labelsUse a descriptive name plus labels such as env and owner; they feed cost reports and organisation policies later.
- Choose region and zoneSelect the region nearest your users and then a zone. For production, plan on running VMs in more than one zone.
- Choose the machine configurationStart with something modest like e2-medium, or define a custom machine type; you can resize once real metrics exist.
- Configure the boot diskPick an image such as Debian 12 or Ubuntu 24.04 LTS, a Balanced persistent disk and a size like 20 GB. Disks are encrypted at rest without any extra step.
- Set the identityCreate or select a dedicated service account that holds only the roles the VM needs, instead of the default Compute Engine service account.
- Configure networkingChoose the VPC and subnet, leave the HTTP and HTTPS boxes cleared unless you need them, and set the external IPv4 address to None for a private VM (add Cloud NAT for outbound access).
- Review the Security settingsTurn on Secure Boot, vTPM and Integrity monitoring, and add the metadata enable-oslogin = TRUE so that SSH access follows IAM.
- Create the VM and connectWhen the green tick appears, connect with browser SSH or gcloud compute ssh --tunnel-through-iap, which works without a public IP.
Tip: after one clean run through the console, turn your choices into Terraform or gcloud commands (see the code references); every further environment then costs a single command.
Common issues after configuration
| Symptom | Likely cause | What to check / fix |
|---|---|---|
| SSH/RDP times out | Traffic cannot reach the VM | Check VPC firewall rules (for IAP, allow ingress on tcp:22 from 35.235.240.0/20), the external IP or Cloud NAT path, and the guest firewall. Connectivity Tests in Network Intelligence Center trace the path. |
| “Permission denied (publickey)” | Missing OS Login role or wrong key | With OS Login the user needs roles/compute.osLogin or osAdminLogin; without it, check the key stored in metadata and the user name. |
| VM never becomes ready | Problem inside the OS | Read the serial output (gcloud compute instances get-serial-port-output), try the interactive serial console, or attach the boot disk to a rescue VM. |
| Service answers on the VM but not from outside | Port, firewall or health check | Verify the process binds to the interface you expect, that an ingress rule applies to this VM, and that Google’s health-check ranges (130.211.0.0/22, 35.191.0.0/16) are permitted. |
| ZONE_RESOURCE_POOL_EXHAUSTED | The zone is out of capacity | Try again later, or switch zone, machine type or region. |
| QUOTA_EXCEEDED | Project quota reached | Ask for a higher limit under IAM & Admin → Quotas. |
| Disk full | The boot or data disk is too small | Raise the size on the disk itself, in the console or with gcloud compute disks resize; the VM can stay up. Then extend the partition and file system from inside the guest. |
| Charges continue after stopping | Leftover resources | A stopped VM no longer bills for vCPU and memory, but disks and reserved external IPs do. Delete what you no longer use. |
| Spot VM vanished | It was preempted | Spot VMs can be stopped at any time. Add a shutdown script, save progress regularly, and let a managed instance group recreate them. |
Use cases: when and where to use it
Good fit
- Application servers that need a runtime, agent or kernel setting a managed platform does not allow
- Rehosting servers from a data centre or another cloud with Migrate to Virtual Machines
- Windows Server and SQL Server on licensed images, or on sole-tenant nodes when you bring your own licences
- Compute-heavy jobs such as rendering, simulation and tightly coupled HPC clusters
- Accelerator-backed machine learning and graphics work on GPU machine types
- Workloads that need an exact vCPU-to-memory ratio (custom machine types)
- Throwaway test and staging machines that a pipeline creates and deletes
Consider something else
- Containers and web apps → Cloud Run
- Event-driven snippets that run for seconds → Cloud Run functions
- Kubernetes → Google Kubernetes Engine (GKE)
- A managed app platform → App Engine
- Hosted relational databases → Cloud SQL or AlloyDB
Pros: why consider it?
Why teams choose it
- Root access to the guest OS, plus your own VPC and disk layout
- Custom machine types, so you pay for the shape you need
- Live migration keeps most VMs running through host maintenance
- A global VPC on Google’s private network
- Sustained and committed use discounts with per-second billing
- Native integration with IAM, Cloud Logging and Cloud Monitoring
Trade-offs to weigh
- Patching the operating system falls to you
- A running VM keeps billing even when idle
- You run and operate more than you would on Cloud Run or App Engine
- Choosing machine sizes and zones is on you
- Guest OS hardening and data protection stay with you
Common threats, vulnerabilities & risks
| Risk | Severity | Why it matters | Mitigation |
|---|---|---|---|
| Ports 22 and 3389 reachable from everywhere | High | Bots sweep the public internet for ports 22 and 3389 and try weak or leaked credentials. | Delete 0.0.0.0/0 rules for ports 22 and 3389; use IAP TCP forwarding with OS Login. |
| Default or over-privileged service account | High | Whoever takes over the VM gets every permission the service account holds. | Create one service account per workload and grant only the roles it needs. |
| Access token taken from the metadata server | High | If the app can be tricked into requesting URLs (SSRF), an attacker can ask the metadata server for the VM’s service-account token. | Keep service accounts minimal, validate outbound URLs, and stop app code from reaching 169.254.169.254. |
| Unpatched operating system | Medium | Known flaws stay exploitable until fixed. | Use VM Manager OS patch management and review Security Command Center findings. |
| Ingress rules with a source of 0.0.0.0/0 | Medium | Internal tools and databases end up answering the public internet. | Target rules by service account or tag, and review them with Firewall Insights. |
| Secrets placed in metadata or startup scripts | Medium | Any process, and any user who can log in, can read metadata values. | Store secrets in Secret Manager and read them with the service account. |
| Project-wide SSH keys and serial console left on | Low–Med | Extra keys and consoles widen who can log in. | Block project-wide keys, switch off serial port access unless needed, and rely on OS Login. |
| Little or no logging | Low–Med | A break-in or misuse stays invisible until much later. | Install the Ops Agent and keep Cloud Audit Logs and VPC Flow Logs on, with alerts in Security Command Center. |
Performance optimisation
- Measure first. Cloud Monitoring metrics and Recommender suggestions show which VMs are over- or under-sized.
- Choose current families such as C4 or N4, and try Arm-based types (Axion C4A, Tau T2A) when your software supports Arm.
- Shape the machine. A custom machine type avoids paying for memory or vCPUs you never use.
- Pick the disk by the bottleneck. Hyperdisk Balanced separates capacity from IOPS and throughput, SSD or Extreme tiers serve heavy database I/O, and Local SSD takes the scratch data.
- Switch on gVNIC and Tier_1 networking where the machine type supports them for higher network bandwidth.
- Use compact placement policies to keep latency-sensitive VMs physically close.
- Know the shared-core limits. Types such as e2-micro and e2-small burst; move sustained, heavy load to standard machine types.
- Add machines, not only size. A managed instance group behind Cloud Load Balancing spreads the load, and Cloud CDN keeps static content near users.
Reduce monthly cost
FinOps is the habit of managing cloud spend together with engineering. These are the FinOps checks that matter most for Compute Engine.
- Commit to the steady baseline. Committed use discounts reward a 1 or 3-year promise (Google advertises roughly 55% to 70%, depending on machine type and term); leave the spiky part on-demand.
- Spot VMs for anything restartable: batch jobs, CI runners and stateless workers. Google quotes discounts of up to about 91% against on-demand.
- Benefit from sustained use discounts. Eligible families that run for much of the month are discounted automatically.
- Act on Recommender. Its idle and oversized VM suggestions show where a smaller machine type would do.
- Attach instance schedules to dev and test VMs so they power off in the evening and at weekends.
- Remember the disks. A stopped VM stops vCPU and memory charges, but its disks keep billing until deleted.
- Tidy up regularly: unattached disks, old snapshots, reserved external IPs that nothing uses, and idle Cloud NAT gateways (external IPv4 addresses are billed hourly).
- Match disk type to need. Balanced Persistent Disk suits most workloads; pay for SSD or Hyperdisk performance only where it matters.
- Keep an eye on egress. Traffic to the internet and between regions adds up, so co-locate chatty services.
- Label and budget. Use labels with Cloud Billing budgets and alerts.
Treat the percentages above as ceilings that Google may revise, and look them up on Google Cloud’s own pricing pages when you plan (see Pricing).
Security optimisation
- Give each workload a dedicated least-privilege service account and avoid the default Compute Engine one.
- Connect with IAP TCP forwarding and OS Login instead of public SSH or RDP, and leave private VMs without an external IP.
- Let private VMs reach the internet through Cloud NAT.
- Write tight firewall rules that target a service account or secure tag rather than wide IP ranges.
- Keep Shielded VM protections on (secure boot, vTPM, integrity monitoring) and consider Confidential VMs for data that must stay encrypted while in use.
- Add customer-managed encryption keys in Cloud KMS if your rules call for them; disks are already encrypted by default.
- Patch through VM Manager and review vulnerability findings in Security Command Center.
- Gather logs with the Ops Agent, and keep Cloud Audit Logs and VPC Flow Logs enabled.
- Hold secrets in Secret Manager, not in metadata or startup scripts.
- Boot only from images your team approved, restricted by the trusted image projects constraint, and rebuild them on a schedule.
- Block project-wide SSH keys and serial port access unless you have a specific need.
Governance & compliance
Guardrails
- A label standard covering owner, environment and cost-center, visible in the billing export
- Organization Policy constraints on where VMs may run, whether they can have external IPs, and which images they may use
- Per-project quotas, plus budget alerts in Cloud Billing
- Folders, projects and a landing zone as the governed base
Organization Policy constraints
- compute.requireOsLogin
- compute.requireShieldedVm
- compute.vmExternalIpAccess
- compute.disableSerialPortAccess
For audit trails use Cloud Audit Logs; for retention use Backup and DR Service or snapshot schedules; and for evidence download reports from Compliance Reports Manager. Compute Engine sits inside Google’s SOC, ISO 27001, PCI DSS and HIPAA-eligibility scope, which speaks for the platform. Whether your own workload complies turns on the guest OS, access rules and data handling that you set up.
Reduce carbon footprint
- Right-size, then stop what is idle. A VM that is not running emits nothing of its own.
- Try Arm. Axion and Tau T2A are Google’s Arm machine types, and Arm cores often draw less power for the same job.
- Favour cleaner regions where latency and data rules allow; Google publishes carbon-free energy figures for each region.
- Let managed instance groups scale in overnight and at weekends instead of holding the peak size.
- Run flexible jobs on Spot VMs to put spare capacity to use.
- Move spiky work off VMs. Cloud Run and Cloud Run functions scale to zero between bursts, so nothing sits idle.
- Read the report. Carbon Footprint in the console breaks your estimated emissions down by project, product and region.
Pricing
Purchase options
On-demand Flexible
Per-second billing with a one-minute minimum and nothing to sign. The default while you learn what the workload really needs.
Committed use discounts Commit
Commit to resources, or to an hourly spend, for 1 or 3 years in return for lower rates.
Spot VMs Cheapest
Surplus Compute Engine capacity sold cheaply; Google can stop the VM whenever it needs the room back. For jobs that can restart.
Sustained use discounts Automatic
A discount applied by itself when an eligible VM runs for a large part of the month.
What you actually pay for
- vCPU and memory, which depend on machine type, region and purchase option
- Disk capacity, any extra provisioned IOPS or throughput, and stored snapshots
- Outbound traffic that leaves Google’s network, and traffic that crosses regions
- Reserved or in-use external IPs, Cloud Load Balancing and Cloud NAT gateways
- Per-hour licence charges on premium operating system and database images
Google reprices by region and over time, so treat the official Compute Engine pricing page and the Google Cloud Pricing Calculator as the source of truth rather than any number quoted here. New accounts should also read the current Free Tier and free-trial terms.
Important code references
Create a small Debian VM with Shielded VM, OS Login, a dedicated service account and no external IP. Replace the placeholder names with your own.
# Create one VM (no external IP)
gcloud compute instances create vm-demo-01 \
--project=my-project-id \
--zone=asia-south1-a \
--machine-type=e2-medium \
--image-family=debian-12 --image-project=debian-cloud \
--boot-disk-size=20GB --boot-disk-type=pd-balanced \
--subnet=snet-app --no-address \
--service-account=vm-demo-sa@my-project-id.iam.gserviceaccount.com --scopes=cloud-platform \
--shielded-secure-boot --shielded-vtpm --shielded-integrity-monitoring \
--metadata=enable-oslogin=TRUE \
--labels=env=dev,owner=platform-team
# List the VMs with their state
gcloud compute instances list --filter="labels.env=dev" \
--format="table(name,zone.basename(),machineType.basename(),status,networkInterfaces[0].networkIP)"
# Connect without a public IP, through Identity-Aware Proxy
gcloud compute ssh vm-demo-01 --zone=asia-south1-a --tunnel-through-iap
# Stop vCPU and memory charges (disks still bill)
gcloud compute instances stop vm-demo-01 --zone=asia-south1-a
# Assumes the subnet and the service account are defined elsewhere
resource "google_compute_instance" "demo" {
name = "vm-demo-01"
machine_type = "e2-medium"
zone = "asia-south1-a"
labels = {
env = "dev"
owner = "platform-team"
}
boot_disk {
initialize_params {
image = "debian-cloud/debian-12"
size = 20
type = "pd-balanced"
}
}
network_interface {
subnetwork = "snet-app"
# no access_config block = no external IP
}
service_account {
email = google_service_account.vm.email
scopes = ["cloud-platform"]
}
shielded_instance_config {
enable_secure_boot = true
enable_vtpm = true
enable_integrity_monitoring = true
}
metadata = {
enable-oslogin = "TRUE"
}
}
# pip install google-cloud-compute
from google.cloud import compute_v1
project, zone, region = "my-project-id", "asia-south1-a", "asia-south1"
instance = compute_v1.Instance(
name="vm-demo-01",
machine_type=f"zones/{zone}/machineTypes/e2-medium",
disks=[compute_v1.AttachedDisk(
boot=True,
auto_delete=True,
initialize_params=compute_v1.AttachedDiskInitializeParams(
source_image="projects/debian-cloud/global/images/family/debian-12",
disk_size_gb=20,
disk_type=f"zones/{zone}/diskTypes/pd-balanced",
),
)],
network_interfaces=[compute_v1.NetworkInterface(
subnetwork=f"projects/{project}/regions/{region}/subnetworks/snet-app",
)], # no access_configs = no external IP
service_accounts=[compute_v1.ServiceAccount(
email=f"vm-demo-sa@{project}.iam.gserviceaccount.com",
scopes=["https://www.googleapis.com/auth/cloud-platform"],
)],
shielded_instance_config=compute_v1.ShieldedInstanceConfig(
enable_secure_boot=True, enable_vtpm=True, enable_integrity_monitoring=True,
),
metadata=compute_v1.Metadata(items=[compute_v1.Items(key="enable-oslogin", value="TRUE")]),
labels={"env": "dev"},
)
operation = compute_v1.InstancesClient().insert(project=project, zone=zone, instance_resource=instance)
operation.result()
print("created", instance.name)
// dotnet add package Google.Cloud.Compute.V1
using Google.Cloud.Compute.V1;
const string project = "my-project-id", zone = "asia-south1-a", region = "asia-south1";
var instance = new Instance
{
Name = "vm-demo-01",
MachineType = $"zones/{zone}/machineTypes/e2-medium",
Disks =
{
new AttachedDisk
{
Boot = true,
AutoDelete = true,
InitializeParams = new AttachedDiskInitializeParams
{
SourceImage = "projects/debian-cloud/global/images/family/debian-12",
DiskSizeGb = 20,
DiskType = $"zones/{zone}/diskTypes/pd-balanced"
}
}
},
NetworkInterfaces = { new NetworkInterface { Subnetwork = $"projects/{project}/regions/{region}/subnetworks/snet-app" } }, // no AccessConfigs = no external IP
ServiceAccounts =
{
new ServiceAccount
{
Email = $"vm-demo-sa@{project}.iam.gserviceaccount.com",
Scopes = { "https://www.googleapis.com/auth/cloud-platform" }
}
},
ShieldedInstanceConfig = new ShieldedInstanceConfig { EnableSecureBoot = true, EnableVtpm = true, EnableIntegrityMonitoring = true },
Metadata = new Metadata { Items = { new Items { Key = "enable-oslogin", Value = "TRUE" } } },
Labels = { ["env"] = "dev" }
};
InstancesClient client = await InstancesClient.CreateAsync();
var operation = await client.InsertAsync(project, zone, instance);
await operation.PollUntilCompletedAsync();
Console.WriteLine("created " + instance.Name);
Best videos to explore
Short walkthrough videos for this service are being prepared. They will appear here and load only when you press play. Until then, follow CloudBrum on YouTube for new videos.
Interview questions
BasicWhat does Compute Engine give you, and what stays your job?
It gives you virtual machines on Google’s hardware, with the image, machine type, disks and network chosen by you. Everything from the operating system upward, including patching, software and backups, remains yours.
BasicWhat happens to billing when you stop a VM?
A stopped VM stops vCPU and memory charges, but its persistent disks and any reserved external IP addresses keep billing. Suspend saves memory to storage (which you pay for), and delete removes the VM and, by default, its boot disk.
BasicWhy does every Compute Engine resource live inside a project?
The project is Google Cloud’s unit of ownership: it carries the billing account, the IAM permissions and the enabled APIs. A VM, its disks and its network interfaces are therefore always billed and governed through one project.
IntermediateWhich disk would you choose for a boot volume, a busy database and a scratch cache?
A Balanced Persistent Disk is a sensible boot volume. A busy database gets Hyperdisk, where capacity, IOPS and throughput are set separately. A scratch cache goes on Local SSD: it is the fastest option but tied to the host, so its contents are gone once the VM stops or is deleted.
IntermediateHow do VPC firewall rules work, and how do they differ from AWS security groups?
VPC firewall rules are stateful, allow or deny, and carry priorities. They are defined on the network and applied to VMs by network tag or service account, rather than being attached to each VM. Ingress is denied by default and egress is allowed.
IntermediateHow do the four Compute Engine purchase options differ?
On-demand needs no paperwork and costs the most per hour. Committed use discounts trade a 1 or 3-year promise (of resources or spend) for a lower rate. Spot VMs cost far less because they use surplus capacity, but Google can stop them, so keep the work restartable. Sustained use discounts need no action at all: they appear on eligible families that run for much of the month.
AdvancedHow would you keep a Compute Engine workload running through a zone outage?
Run a regional managed instance group across several zones behind Cloud Load Balancing, with autohealing health checks, keep state outside the VMs (Cloud SQL, Cloud Storage, Filestore), and rehearse failover. Live migration covers most planned host maintenance without a restart; check the current SLA terms.
AdvancedShielded VM or Confidential VM: what does each one protect?
Shielded VM guards the boot chain, using secure boot, a virtual TPM and integrity monitoring, so a tampered image or rootkit is detected. Confidential VM goes a step further and keeps memory encrypted by the hardware while the data is being processed.
AdvancedHow do engineers reach a private VM that has no external IP?
Through Identity-Aware Proxy TCP forwarding combined with OS Login (for example gcloud compute ssh --tunnel-through-iap), or over Cloud VPN or Interconnect from the corporate network. IAM roles decide who gets in, each session is logged, and no inbound port faces the internet.
Similar or alternative services on other clouds
| Capability | AWS | Azure | Google Cloud |
|---|---|---|---|
| Service | Amazon EC2 | Azure Virtual Machines | Compute Engine |
| Auto scaling | Auto Scaling groups | Virtual Machine Scale Sets | Managed instance groups |
| Machine images | AMI | Managed images, Azure Compute Gallery | Custom images, image families |
| Discounted spare capacity | Spot Instances | Spot VMs | Spot VMs |
| Commitment discounts | Savings Plans, Reserved Instances | Reservations, Savings plan for compute | Committed use discounts |
| Arm-based options | Graviton | Ampere Altra and Cobalt 100-based VMs | Tau T2A, Axion-based C4A |
| Keyless admin access | Session Manager | Azure Bastion | Identity-Aware Proxy (IAP) TCP forwarding |
Not sure virtual machines are the right level? Compare with Cloud Run (containers and web apps), Cloud Run functions (serverless functions), Google Kubernetes Engine (Kubernetes) and App Engine (managed app platform).
Did you find this article helpful?
Your answer helps us improve this page for the next reader.
Sources and further reading
CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.
- Compute Engine documentationGoogle Cloud
- Compute Engine pricingGoogle Cloud
- Machine families resource and comparison guideGoogle Cloud
- Google Cloud Architecture FrameworkGoogle Cloud
- Compute Engine Service Level AgreementGoogle Cloud
- gcloud compute instances createGoogle Cloud
- Terraform Google provider: google_compute_instanceHashiCorp
- Compute Engine client library for PythonGoogle Cloud
- Compute Engine client library for .NETGoogle Cloud
