Use routes

This page describes how to create and manage routes forVirtual Private Cloud (VPC) networks in Google Cloud. This page assumes that youare familiar with the different types of Google Cloud routes and theircharacteristics as described inRoutes.

Every new network has two types of system-generated routes: adefaultroute, which you can remove or replace, andonesubnet route for each of its subnets. You cannotremove a subnet route unless you delete the corresponding subnet itself.

In addition to the system-generated routes, you can create othercustomstatic routes.

List routes for a VPC network

You can use the Google Cloud CLI or the API to list and view details about thefollowing types of routes:

Neither the gcloud CLI commands nor the API methods show thefollowing types of routes:

To see the complete route view, use the Google Cloud console. To list anddescribe policy-based routes, seeUse policy-basedroutes.

Console

  1. In the Google Cloud console, go to theRoutes page.

    Go to Routes

  2. On theEffective routes tab, do the following:

    • Choose a VPC network.
    • Choose a region.
  3. ClickView.

  4. You can filter on properties includingroute type, destination IP range,andnext hop type.

  5. Optional: Click theShow suppressed routes toggle to the onposition to view routes that are suppressed. To view the reason why aroute is suppressed, point to the icon in theStatus column.

gcloud

To list and view details forsubnet routesandstatic routes, use thegcloud computeroutes commands. These commands don'tshow other types of routes. To see all routes, use the Google Cloud console.

To list routes, do the following:

gcloud compute routes list \    --filter="network=NETWORK_NAME" \    --project=PROJECT_ID

To get details for a route, do the following:

gcloud compute routes describeROUTE_NAME \    --format="flattened()" \    --project=PROJECT_ID

Replace the following:

  • NETWORK_NAME: the name of the VPC network
  • PROJECT_ID: the project ID that contains yourVPC network
  • ROUTE_NAME: the name of the route

API

To list and view details forsubnet routesandstatic routes, use theroutes.list androutes.get methods. These methodsdon't show other types of routes. To see all routes, use the Google Cloud console.

To list routes, do the following:

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/routes?filter=network="NETWORK_URL

To get details for a route, do the following:

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/routes/ROUTE_NAME

Replace the following:

  • PROJECT_ID: the project ID that contains yourVPC network
  • NETWORK_URL: the URL of the VPC network
  • ROUTE_NAME: the name of the route

List applicable routes for a VM network interface

You can use the Google Cloud console to view applicable routes for a VM'snetwork interface. This view narrows the list of routes that you can use foregress traffic.

To view applicable routes for a specific network interface of a VM, followthese steps.

Console

  1. In the Google Cloud console, go to theVM instances page.

    Go to VM instances

  2. Locate a VM instance in the list. In theMore actions menu at theend of the row, selectView network details.

  3. If an instance has multiple network interfaces, in theNetwork interface details section, select the network interfacethat you want to view.

  4. In theFirewall and routes details section, click theRoutes tab tosee all the routes that apply to the network interface, sorted by route name.

Add and remove static routes

You can add or remove static routes and policy-based routes that are local toyour VPC network. This section describes how to add and deletelocal static routes. For more information about how to add and removepolicy-based routes, seeUse policy-based routes.

Subnet routes are added and deleted automatically when you add or delete asubnet. For more information about how to add and remove subnets, seeWork with subnets.

All routes in a VPC network that are connected byVPC Network Peering must be manipulated in the VPC networkthat exports those routes. For more information, seeRoute exchangeoptions.

Important: Static routes cannot be modified after creation. Instead, delete theroute and create a replacement route.

Before you add a static route

Before you add a static route, consider the following:

Note: For next hops that use Cloud Router, you can optionally usecustom learned routes as an alternative to static routes. Unlike static routes,custom learned routes are suppressed automatically if their associated BGPsession is disrupted. This behavior allows alternate routes to be used in caseof a network outage and might prevent your traffic from being dropped.Also, unlike static routes, custom learned routes can be used overCloud Interconnect VLAN attachments and HA VPN tunnels. Formore information, seeCustom learned routes.This feature is inPreview.

Add a static route

Add a static route to a network. For more information about the different types of staticroute next hops, including which ones support IPv6 destinations, seeNext hops and features.

Console

  1. In the Google Cloud console, go to theRoutes page.

    Go to Routes

  2. Click theRoute management tab.

  3. ClickCreate route.

  4. Specify a name and a description for the route.

  5. In theNetwork list, select an existing network for the route.

  6. In theRoute type list, selectStatic route.

  7. In theIP version list, select the required IP version:

    • To create an IPv4 static route, selectIPv4.
    • To create an IPv6 static route, selectIPv6.
  8. Specify a destination IP range. The broadest possible destination is0.0.0.0/0 for IPv4 or::/0 for IPv6.

  9. Specify apriority for the route.The priority can be from0 (the highest priority) to65535 (thelowest priority).

  10. To make the route applicable only to select instances with matchingnetwork tags, specify those in theInstance tags field. Leave thefield blank to make the route applicable to all instances in the network.

  11. Select anext hop for theroute:

    • Default internet gateway: delivers packets to the internet and toGoogle APIs and services
    • Specify an instance: delivers packets to a VM instance'snetwork interface. Specify the VM instance by name and zone. If theroute destination is an IPv6 address, the VM instance must bedual-stack orIPv6-only.
    • Specify IP address of an instance: specify an IP address of anexisting instance in the VPC network. For IPv6static routes, the instance must bedual-stack orIPv6-only. For importantrestrictions for valid next hop IP addresses, seestatic route nexthops.
    • Specify VPN tunnel: delivers packets to an existingClassic VPNtunnelusing static routing.
    • Specify a forwarding rule of aninternal passthrough Network Load Balancer: delivers packets to aninternal passthrough Network Load Balancerthat is specified by its internal forwarding rule name and region.The forwarding rule can have an IPv4 or IPv6 address.The IP version of the forwarding rule that you specify must match theIP version of the static route that you create.
  12. ClickCreate.

gcloud

Create a new custom static route with the following gcloud CLIcommand:

gcloud compute routes createROUTE_NAME \    --network=NETWORK \    --destination-range=DESTINATION_RANGE \    --priority=PRIORITY \NEXT_HOP_SPECIFICATION

Replace the following:

  • ROUTE_NAME: the name of the route
  • NETWORK: the name of the VPCnetwork that contains the route
  • DESTINATION_RANGE: the destination IPv4 or IPv6addresses to which this route applies. The broadest possible destinationis0.0.0.0/0 for IPv4 or::/0 for IPv6.
  • PRIORITY: the routepriority, which can be from0(the highest priority) to65535 (the lowest priority)
  • NEXT_HOP_SPECIFICATION: thenext hopfor the static route. Use one of the following parameters or combinationof parameters:

    • --next-hop-gateway=default-internet-gateway: deliver packets to theinternet and to Google APIs and services.
    • --next-hop-instance=INSTANCE_NAME and--next-hop-instance-zone=ZONE: deliverpackets to an existing VM instance's network interface. Specify theVM instance by name and zone. If the route destination is anIPv6 address, the VM instance must bedual-stack orIPv6-only.
    • --next-hop-address=ADDRESS: specify an IPaddress of anexisting instance in the VPC network.For IPv6 static routes, the instance must bedual-stack orIPv6-only. Forimportant restrictions for valid next hop IP addresses, seeNext hops and features.
    • --next-hop-vpn-tunnel=VPN_TUNNEL_NAME and--next-hop-vpn-tunnel-region=REGION: deliverpackets to an existingClassic VPNtunnelusing static routing.
    • --next-hop-ilb=FORWARDING_RULE and--next-hop-ilb-region=REGION: deliver packetsto aninternal passthrough Network Load Balancer.Specify the forwarding rule by its name (or IPv4 or IPv6 address)and region. The IP version of the forwarding rule that you specifymust match the IP version of the static route that you create. Formore information about configuring static routes to internal passthrough Network Load Balancers,seeCreate static routes.

    To make the custom static route apply to only select VMs by network tag,add the--tags flag and specify one or more network tags. For moreinformation about how network tags and custom static routes work together,seeApplicable routes in the Routesoverview. You can use tags with any custom static route.

For more information about the gcloud CLI syntax, see theSDK documentation.

API

Create a new custom static route.

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/routes{  "name": "ROUTE_NAME",  "network": "NETWORK_NAME",  "destRange": "DESTINATION_RANGE",  "priority":PRIORITY,  "NEXT_HOP_SPECIFICATION"}

Replace the following:

  • PROJECT_ID: the ID of the project where your routeis created
  • ROUTE_NAME: the name of the route
  • NETWORK: the name of the VPCnetwork that contains the route.
  • DESTINATION_RANGE: the destination IPv4 or IPv6address range to which this route applies. The broadest possibledestination is0.0.0.0/0 for IPv4 or::/0 for IPv6.
  • PRIORITY: the routepriority, which can be from0(the highest priority) to65535 (the lowest priority)
  • NEXT_HOP_SPECIFICATION: thenexthop for the static route. Useone of the following parameters or combination of parameters:
    • nextHopGateway: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/gateways/default-internet-gateway:delivers packets to the internet and to Google APIs and services
    • nextHopInstance: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME:delivers packets to a VM instance's network interface. Specify the VMinstance by name and zone. If the route destination is an IPv6address, the VM instance must bedual-stackorIPv6-only.
    • nextHopIp:ADDRESS: specify an IP address ofanexisting instance in the VPC network. For IPv6static routes, the instance must bedual-stack orIPv6-only. For importantrestrictions for valid next hop IP addresses, seeNext hops andfeatures.
    • nextHopVpnTunnel: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/vpnTunnels/VPN_TUNNEL_NAME:delivers packets to an existingClassic VPNtunnelusing static routing.
    • nextHopIlb: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/forwardingRules/FORWARDING_RULE:delivers packets to aninternal passthrough Network Load Balancer.Specify the forwarding rule by its name (or IPv4 or IPv6 address)and region. The IP version of the forwarding rule that you specifymust match the IP version of the static route that you create.

To make the custom static route apply to only select VMs by network tag,add thetags field and specify one or more network tags. For moreinformation about how network tags and custom static routes work together,seeApplicable routes in the Routesoverview. You can use tags with any custom static route.

For more information, refer to theroutes.insert method.

Terraform

You can create a static route by using aTerraform module.

This static route creates a default route to the internet.

module "google_compute_route" {  source       = "terraform-google-modules/network/google//modules/routes"  version      = "~> 13.0"  project_id   = var.project_id # Replace this with your project ID in quotes  network_name = "default"  routes = [    {      name              = "egress-internet"      description       = "route through IGW to access internet"      destination_range = "0.0.0.0/0"      tags              = "egress-inet"      next_hop_internet = "true"    }  ]}

To learn how to apply or remove a Terraform configuration, seeBasic Terraform commands.

Go

import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// createRoute creates a route with given name inside given project.funccreateRoute(wio.Writer,projectID,namestring)error{// projectID := "your_project_id"// name := "testname"ctx:=context.Background()client,err:=compute.NewRoutesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewRoutesRESTClient: %w",err)}deferclient.Close()route:=&computepb.Route{Name:proto.String(name),Network:proto.String("global/networks/default"),DestRange:proto.String("0.0.0.0/0"),NextHopGateway:proto.String("global/gateways/default-internet-gateway"),}req:=&computepb.InsertRouteRequest{Project:projectID,RouteResource:route,}op,err:=client.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to insert a route: %w",err)}iferr:=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Route created\n")returnnil}

Java

importcom.google.cloud.compute.v1.InsertRouteRequest;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Route;importcom.google.cloud.compute.v1.RoutesClient;importjava.io.IOException;importjava.util.UUID;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateRoute{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// Project ID or project number of the Cloud project you want to use.StringprojectId="your-project-id";// Route name you want to use.StringrouteName="your-route-name";createRoute(projectId,routeName);}// Create route for a project.publicstaticOperation.StatuscreateRoute(StringprojectId,StringrouteName)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests.try(RoutesClientroutesClient=RoutesClient.create()){StringnextHopGateway=String.format("projects/%s/global/gateways/default-internet-gateway",projectId);Routeroute=Route.newBuilder().setName(routeName).setDestRange("10.0.0.0/16").setNetwork("global/networks/default").setNextHopGateway(nextHopGateway).build();InsertRouteRequestrequest=InsertRouteRequest.newBuilder().setProject(projectId).setRequestId(UUID.randomUUID().toString()).setRouteResource(route).build();returnroutesClient.insertCallable().futureCall(request).get(30,TimeUnit.SECONDS).getStatus();}}}

Python

from__future__importannotationsimportsysfromtypingimportAnyfromgoogle.api_core.extended_operationimportExtendedOperationfromgoogle.cloudimportcompute_v1defwait_for_extended_operation(operation:ExtendedOperation,verbose_name:str="operation",timeout:int=300)->Any:"""    Waits for the extended (long-running) operation to complete.    If the operation is successful, it will return its result.    If the operation ends with an error, an exception will be raised.    If there were any warnings during the execution of the operation    they will be printed to sys.stderr.    Args:        operation: a long-running operation you want to wait on.        verbose_name: (optional) a more verbose name of the operation,            used only during error and warning reporting.        timeout: how long (in seconds) to wait for operation to finish.            If None, wait indefinitely.    Returns:        Whatever the operation.result() returns.    Raises:        This method will raise the exception received from `operation.exception()`        or RuntimeError if there is no exception set, but there is an `error_code`        set for the `operation`.        In case of an operation taking longer than `timeout` seconds to complete,        a `concurrent.futures.TimeoutError` will be raised.    """result=operation.result(timeout=timeout)ifoperation.error_code:print(f"Error during{verbose_name}: [Code:{operation.error_code}]:{operation.error_message}",file=sys.stderr,flush=True,)print(f"Operation ID:{operation.name}",file=sys.stderr,flush=True)raiseoperation.exception()orRuntimeError(operation.error_message)ifoperation.warnings:print(f"Warnings during{verbose_name}:\n",file=sys.stderr,flush=True)forwarninginoperation.warnings:print(f" -{warning.code}:{warning.message}",file=sys.stderr,flush=True)returnresultdefcreate_route(project_id:str,network:str,route_name:str,destination_range:str,*,next_hop_gateway:str|None=None,next_hop_ip:str|None=None,next_hop_instance:str|None=None,next_hop_vpn_tunnel:str|None=None,next_hop_ilb:str|None=None,)->compute_v1.Route:"""    Create a new route in selected network by providing a destination and next hop name.    Note: The set of {next_hop_gateway, next_hop_ip, next_hop_instance, next_hop_vpn_tunnel,        next_hop_ilb} is exclusive, you and only specify one of those parameters.    Args:        project_id: project ID or project number of the Cloud project you want to use.        network: name of the network the route will be created in. Available name formats:            * https://www.googleapis.com/compute/v1/projects/{project_id}/global/networks/{network}            * projects/{project_id}/global/networks/{network}            * global/networks/{network}        route_name: name of the new route.        destination_range: range of destination IPs this route should be applied to. E.g. 10.0.0.0/16.        next_hop_gateway: name of the gateway the traffic should be directed to.        next_hop_ip: IP address the traffic should be directed to.        next_hop_instance: name of the instance the traffic should be directed to. Name format:            "projects/{project}/zones/{zone}/instances/{instance_name}"        next_hop_vpn_tunnel: name of the VPN tunnel the traffic should be directed to. Name format:            "projects/{project}/regions/{region}/vpnTunnels/{vpn_tunnel_name}"        next_hop_ilb: name of a forwarding rule of the Internal Load Balancer the traffic            should be directed to. Name format:            "projects/{project}/regions/{region}/forwardingRules/{forwarding_rule_region}"    Returns:        A new compute_v1.Route object.    """excl_args={next_hop_instance,next_hop_ilb,next_hop_vpn_tunnel,next_hop_gateway,next_hop_ip,}args_set=sum(1ifargisnotNoneelse0forarginexcl_args)ifargs_set!=1:raiseRuntimeError("You must specify exactly one next_hop_* parameter.")route=compute_v1.Route()route.name=route_nameroute.network=networkroute.dest_range=destination_rangeifnext_hop_gateway:route.next_hop_gateway=next_hop_gatewayelifnext_hop_ip:route.next_hop_ip=next_hop_ipelifnext_hop_instance:route.next_hop_instance=next_hop_instanceelifnext_hop_vpn_tunnel:route.next_hop_vpn_tunnel=next_hop_vpn_tunnelelifnext_hop_ilb:route.next_hop_ilb=next_hop_ilbroute_client=compute_v1.RoutesClient()operation=route_client.insert(project=project_id,route_resource=route)wait_for_extended_operation(operation,"route creation")returnroute_client.get(project=project_id,route=route_name)

Add an IPv4 default route

The IPv4 default static route (0.0.0.0/0) with thenext-hop-gateway set todefault-internet-gateway is automatically configured for eachVPC network. Use these steps to re-create this route ifnecessary.

Console

  1. In the Google Cloud console, go to theRoutes page.

    Go to Routes

  2. Click theRoute management tab.

  3. ClickCreate route.

  4. Specify a name and a description for the route.

  5. Select an existing network for the route.

  6. ForDestination IP range, enter0.0.0.0/0.

  7. Specify a priority for the route. The priority can be from0 (thehighest priority) to65535 (the lowest priority).

  8. ForNext hop, selectDefault internet gateway.

  9. ClickCreate.

gcloud

Recreate the IPv4 default route for a network.

gcloud compute routes createROUTE_NAME \    --destination-range=0.0.0.0/0 \    --network=NETWORK \    --next-hop-gateway=default-internet-gateway

Replace the following:

  • ROUTE_NAME: a name for the route
  • NETWORK: the name of the VPCnetwork that contains the route

API

Recreate the IPv4 default route for a network.

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/routes{  "destRange": "0.0.0.0/0",  "name": "ROUTE_NAME",  "network": "NETWORK_NAME",  "nextHopGateway": "projects/PROJECT_ID/global/gateways/default-internet-gateway"}

Replace the following:

  • PROJECT_ID: the ID of the project where your routeis created
  • ROUTE_NAME: a name for the route
  • NETWORK_NAME: the name of the VPCnetwork that contains the route

Add an IPv6 default route

The IPv6 default static route (::/0) withthenext-hop-gateway set todefault-internet-gateway is automaticallyconfigured for the VPC network when you create a subnet with theIPv6 access type set to external. You candelete the route toblock all IPv6 traffic from VMs to the internet. You can also recreate the routeif needed.

Console

  1. In the Google Cloud console, go to theRoutes page.

    Go to Routes

  2. Click theRoute management tab.

  3. ClickCreate route.

  4. Specify a name and a description for the route.

  5. Select an existing network for the route.

  6. ForDestination IP range, enter::/0.

  7. Specify apriority for the route.The priority can be from0 (the highest priority) to65535 (thelowest priority).

  8. ForNext hop, selectDefault internet gateway.

  9. ClickCreate.

gcloud

Recreate the IPv6 default route for a network.

gcloud compute routes createROUTE_NAME \    --destination-range=::/0 \    --network=NETWORK \    --next-hop-gateway=default-internet-gateway

Replace the following:

  • ROUTE_NAME: a name for the route.
  • NETWORK: the name of the VPCnetwork that contains the route.

API

Recreate the IPv6 default route for a network.

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/routes{  "destRange": "::/0",  "name": "ROUTE_NAME",  "network": "NETWORK_NAME",  "nextHopGateway": "projects/PROJECT_ID/global/gateways/default-internet-gateway"}

Replace the following:

  • PROJECT_ID: the ID of the project where your routeis created
  • ROUTE_NAME: a name for the route
  • NETWORK_NAME: the name of the VPCnetwork that contains the route

Modify a static route

You cannot edit or update a static route after you create it. To modify astatic route, you must delete it and create a replacement.

Delete a static route

To delete a route, do the following.

Console

  1. In the Google Cloud console, go to theRoutes page.

    Go to Routes

  2. Click theRoute management tab.

  3. Select the checkbox next to the rule that you want to delete.

  4. ClickDelete.

  5. ClickDelete again to confirm.

gcloud

Delete a custom static route by using the following gcloud CLIcommand:

gcloud compute routes deleteROUTE_NAME

ReplaceROUTE_NAME with the name of the routethat you want to delete.

API

Delete a custom static route to remove it from your VPCnetwork by using theroutes.delete method:

DELETE https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/routes/ROUTE_NAME

Replace the following:

  • PROJECT_ID: the ID of the project where yourroute is located.
  • ROUTE_NAME: the name of the route to delete.

Go

import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb")// deleteRoute deletes a route by name in given project.funcdeleteRoute(wio.Writer,projectID,namestring)error{// projectID := "your_project_id"// name := "testname"ctx:=context.Background()client,err:=compute.NewRoutesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewRoutesRESTClient: %w",err)}deferclient.Close()req:=&computepb.DeleteRouteRequest{Project:projectID,Route:name,}op,err:=client.Delete(ctx,req)iferr!=nil{returnfmt.Errorf("unable to delete a route: %w",err)}iferr:=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Route deleted\n")returnnil}

Java

importcom.google.cloud.compute.v1.DeleteRouteRequest;importcom.google.cloud.compute.v1.RoutesClient;importjava.io.IOException;importjava.util.UUID;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassDeleteRoute{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// Project ID or project number of the Cloud project you want to use.StringprojectId="your-project-id";// Route name you want to delete.StringrouteName="your-route-name";deleteRoute(projectId,routeName);}// Deletes a route from a project.publicstaticvoiddeleteRoute(StringprojectId,StringrouteName)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests.try(RoutesClientroutesClient=RoutesClient.create()){DeleteRouteRequestrequest=DeleteRouteRequest.newBuilder().setProject(projectId).setRoute(routeName).setRequestId(UUID.randomUUID().toString()).build();routesClient.deleteCallable().futureCall(request).get(30,TimeUnit.SECONDS);}}}

Python

from__future__importannotationsimportsysfromtypingimportAnyfromgoogle.api_core.extended_operationimportExtendedOperationfromgoogle.cloudimportcompute_v1defwait_for_extended_operation(operation:ExtendedOperation,verbose_name:str="operation",timeout:int=300)->Any:"""    Waits for the extended (long-running) operation to complete.    If the operation is successful, it will return its result.    If the operation ends with an error, an exception will be raised.    If there were any warnings during the execution of the operation    they will be printed to sys.stderr.    Args:        operation: a long-running operation you want to wait on.        verbose_name: (optional) a more verbose name of the operation,            used only during error and warning reporting.        timeout: how long (in seconds) to wait for operation to finish.            If None, wait indefinitely.    Returns:        Whatever the operation.result() returns.    Raises:        This method will raise the exception received from `operation.exception()`        or RuntimeError if there is no exception set, but there is an `error_code`        set for the `operation`.        In case of an operation taking longer than `timeout` seconds to complete,        a `concurrent.futures.TimeoutError` will be raised.    """result=operation.result(timeout=timeout)ifoperation.error_code:print(f"Error during{verbose_name}: [Code:{operation.error_code}]:{operation.error_message}",file=sys.stderr,flush=True,)print(f"Operation ID:{operation.name}",file=sys.stderr,flush=True)raiseoperation.exception()orRuntimeError(operation.error_message)ifoperation.warnings:print(f"Warnings during{verbose_name}:\n",file=sys.stderr,flush=True)forwarninginoperation.warnings:print(f" -{warning.code}:{warning.message}",file=sys.stderr,flush=True)returnresultdefdelete_route(project_id:str,route_name:str)->None:"""    Delete a route in project.    Args:        project_id: project ID or project number of the Cloud project you want to use.        route_name: name of the route to delete.    """route_client=compute_v1.RoutesClient()operation=route_client.delete(project=project_id,route=route_name)wait_for_extended_operation(operation,"route deletion")

Propagation of route changes

When you add or delete a static route, the route propagates to all regionsand VM instances in your VPC network. A route operationstatus ofPENDING orRUNNING indicates that the route change is queued.

After queueing, the route operation status changes toDONE. Itmight take an additional 30 seconds before all VM instances in yourVPC network and VPC Network Peering networksuse a new route or stop using an old route.

If you add or remove several static routes simultaneously, the changes can beapplied in any order. There is no guarantee that the order in which you submitroute changes is the order in which they are processed. Different instancesmight become aware of the changes at different times.

If you need to make route changes that depend on each other, you must make thosechanges sequentially by performing subsequent changes only after the previouschange's status isDONE and an additional 30 seconds has elapsed.

Enable IP forwarding for instances

By default, IP forwarding is disabled, and Google Cloud performs strictsource address checking. Subject to the effective egress firewall configuration,a VM can emit packets with the following sources:

  • The primary internal IPv4 address of an instance's network interface (NIC).
  • Any configured alias IP range on an instance's NIC.
  • If an IPv6 address range is configured on the subnet, and the instance isdual-stack or IPv6-only,any of the IPv6 addresses that are assigned to the NIC.
  • An internal or external IP address associated with a forwarding rule, forpass-through load balancing or protocol forwarding, if the instance is abackend for an internal passthrough Network Load Balancer, an external passthrough Network Load Balancer, or is referenced by atarget instance.

To use a VM as a next hop for a route, the VM needs to forward packets whosesources don't match one of the IP addresses or ranges in the preceding list. Toforward packets with arbitrary source addresses, you must enable IP forwarding:

  • When you create or update a VM, you enable IP forwarding by following thedirections in this section. Enabling IP forwarding applies to all of the NICson the VM.
  • In addition to the steps in this section, you must enable IP forwardingwithin the VM guest operating system. To do this on Linux, set the value ofone or both of the following kernel parameters to1:net.ipv4.ip_forward(for IPv4) ornet.ipv6.conf.all.forwarding (for IPv6).

To enable IP forwarding when you create a VM, complete the following steps.

Console

  1. In the Google Cloud console, go to theVM instances page.

    Go to VM instances

  2. ClickCreate instance.

  3. In theAdvanced options section, expandNetworking, disks, security,management, sole-tenancy.

  4. Expand theNetworking section.

  5. In theIP forwarding section, select theEnable checkbox.

gcloud

When creating an instance, add the--can-ip-forward flag to your command:

gcloud compute instances create ... --can-ip-forward

API

When creating an instance, use thecanIpForward field to enable IPforwarding:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances{  "canIpForward": true,  ...other fields}

Replace the following:

  • PROJECT_ID: the ID of the project that containsthe instance
  • ZONE: the Google Cloud zone containing theinstance

For more information, see theinstances.insert method.

Terraform

You can use theTerraformresourceto create a VM instance with IP forwarding enabled.

In this example, the Terraform arguments have assigned values that you canchange.

resource "google_compute_instance" "default" {  project      = var.project_id # Replace this with your project ID in quotes  zone         = "southamerica-east1-b"  name         = "instance-next-hop"  machine_type = "e2-medium"  boot_disk {    initialize_params {      image = "debian-cloud/debian-9"    }  }  network_interface {    network = "default"  }  can_ip_forward = true}

To learn how to apply or remove a Terraform configuration, seeBasic Terraform commands.

After you enable IP forwarding,continue with the VM creationprocess.

To enable IP forwarding on an existing VM,update thecanIpForwardinstance property.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.