CareerByteCode
ByteBlogby CareerByteCode

Google Cloud VPC for Beginners: Subnets, Routes and Firewalls

What you build: a custom VPC with two subnets and firewall rules, in your own Google Cloud account. Every step, command and screenshot explained for beginners.

Google Cloud VPC for Beginners: Subnets, Routes and Firewalls

✍️ Translate this blog into Hindi, Tamil or Telugu

In this lab you build your own network in Google Cloud: a custom VPC with two subnets, the routes that come with it, and firewall rules that you test with two real virtual machines. A ping between the VMs fails, you add one firewall rule and it works, you prove the rule works in one direction only, and you see why a VM without a public IP cannot reach the internet. You finish by deleting everything.

Who it is for: beginners who see "VPC", "subnet" and "firewall" in every cloud course and want to understand them by testing. Time: about 1 hour. Cost: free tier or a few cents (one e2-micro VM in us-east1 is in the Always Free tier; the second one runs for about 15 minutes; VPCs, subnets, routes and firewall rules have no charge).

Every command below was run for real by the CareerByteCode Team on a fresh Google Cloud project, and every output and screenshot is the real result we got. We ran the commands from a terminal with the Google Cloud CLI; Cloud Shell in your browser has the same tools, so you can copy and paste each command there.

🧪⭐ Recommended by CareerByteCode · ByteLabs project bundleCloud and DevOps Realtime Starterโ‚น499Build the projects →

Part A: networking in plain English

Your own network in Google Cloud
The VPC, its two subnets, the routes and the firewall rules of this lab
  • VPC (Virtual Private Cloud): your private network inside Google Cloud. In Google Cloud a VPC is global: one VPC can have subnets in many regions.
  • Subnet: a range of private IP addresses in one region, written in CIDR form. 10.10.1.0/24 means the 256 addresses from 10.10.1.0 to 10.10.1.255 (Google keeps 4 of them for itself).
  • Custom mode: you create every subnet yourself. (Auto mode creates one subnet in every region for you; good for quick tests, bad for planning.)
  • Route: a rule that says where packets for an address range go. Google adds a route for every subnet and one default route (0.0.0.0/0) to the internet gateway.
  • Firewall rule: decides which packets may enter (ingress) or leave (egress) a VM. Every VPC denies all incoming traffic and allows all outgoing traffic by default. Rules can target VMs by network tag (like db).
  • IAP (Identity-Aware Proxy) TCP forwarding: lets you SSH into VMs that have no public IP, through Google. Its traffic comes from 35.235.240.0/20.

Real-life example: an office building. The VPC is the building, subnets are floors, routes are the corridors and lifts, and firewall rules are the guards at each door who check a list before letting anyone in. A room with no window to the street (no public IP) cannot shout to people outside.

Before you start

  1. A Google Cloud account (the free trial works) and a project with billing linked.
  2. Open Cloud Shell (the >_ icon at the top of the Google Cloud console).
  3. Save your project id (put your own id between the quotes):
export PROJECT_ID="your-project-id"
  1. The first time you run gcloud compute ssh, gcloud creates an SSH key for you: press Enter at the passphrase questions (or choose a passphrase).

Part B: the lab

Step 1: turn on the APIs and create a custom VPC

Why: Compute Engine runs the VMs and owns networking; IAP lets us SSH without public IPs. --subnet-mode=custom means no subnets are created yet. gcloud even suggests firewall commands, because a new VPC lets nothing in.

gcloud config set project $PROJECT_ID
gcloud services enable compute.googleapis.com iap.googleapis.com
gcloud compute networks create cbc-vpc --subnet-mode=custom 2>&1 | tail -3
Updated property [core/project].
Operation "operations/acat.p2-PROJECT_NUMBER-8154d7b0-daaf-48b3-9bfa-57ce4fe3bca9" finished successfully.
$ gcloud compute firewall-rules create <FIREWALL_NAME> --network cbc-vpc --allow tcp,udp,icmp --source-ranges <IP_RANGE>
$ gcloud compute firewall-rules create <FIREWALL_NAME> --network cbc-vpc --allow tcp:22,tcp:3389,icmp

Step 2: two subnets, web and db

Why: in real life the web servers and the database live in different subnets so you can control traffic between them.

gcloud compute networks subnets create web-subnet --network=cbc-vpc --region=us-east1 --range=10.10.1.0/24 2>&1 | tail -2
gcloud compute networks subnets create db-subnet --network=cbc-vpc --region=us-east1 --range=10.10.2.0/24 2>&1 | tail -2
gcloud compute networks subnets list --network=cbc-vpc --format="table(name,region.basename(),ipCidrRange)"
NAME        REGION    NETWORK  RANGE         STACK_TYPE  IPV6_ACCESS_TYPE  INTERNAL_IPV6_PREFIX  EXTERNAL_IPV6_PREFIX
web-subnet  us-east1  cbc-vpc  10.10.1.0/24  IPV4_ONLY
NAME       REGION    NETWORK  RANGE         STACK_TYPE  IPV6_ACCESS_TYPE  INTERNAL_IPV6_PREFIX  EXTERNAL_IPV6_PREFIX
db-subnet  us-east1  cbc-vpc  10.10.2.0/24  IPV4_ONLY
NAME        REGION    RANGE
db-subnet   us-east1  10.10.2.0/24
web-subnet  us-east1  10.10.1.0/24
VPC and subnets
Steps 1 and 2: cbc-vpc with web-subnet 10.10.1.0/24 and db-subnet 10.10.2.0/24

Step 3: the routes Google made for you

gcloud compute routes list --filter="network:cbc-vpc" --format="table(name.slice(0:30).join(\"\"),destRange,nextHopGateway.basename(),nextHopNetwork.basename(),priority)"
NAME                            DEST_RANGE    NEXT_HOP_GATEWAY          NEXT_HOP_NETWORK  PRIORITY
default-route-78a202811268752a  0.0.0.0/0     default-internet-gateway                    1000
default-route-r-84b25c66d34ae1  10.10.2.0/24                            cbc-vpc           0
default-route-r-c017f0b3206cad  10.10.1.0/24                            cbc-vpc           0
Routes
Step 3: one route per subnet and a default route to the internet gateway

Three routes: one for each subnet (priority 0, inside the VPC) and the default route 0.0.0.0/0 to the default-internet-gateway. Remember this one: it exists, yet in Step 10 the internet will still be out of reach. Why? Read on.

Step 4: firewall, allow SSH only from Google IAP

Why: we never open SSH to the whole internet (0.0.0.0/0). Only Google's IAP range may reach port 22.

gcloud compute firewall-rules create cbc-allow-ssh-iap --network=cbc-vpc \
  --direction=INGRESS --action=ALLOW --rules=tcp:22 --source-ranges=35.235.240.0/20 2>&1 | tail -2
gcloud compute firewall-rules list --filter="network:cbc-vpc" --format="table(name,direction,sourceRanges.list(),allowed[].map().firewall_rule().list(),targetTags.list())"
NAME               NETWORK  DIRECTION  PRIORITY  ALLOW   DENY  DISABLED
cbc-allow-ssh-iap  cbc-vpc  INGRESS    1000      tcp:22        False
NAME               DIRECTION  SOURCE_RANGES    ALLOW   TARGET_TAGS
cbc-allow-ssh-iap  INGRESS    35.235.240.0/20  tcp:22
SSH rule
Step 4: tcp:22 allowed from 35.235.240.0/20 only

Step 5: two small VMs with no public IP

Why: --no-address gives no public IP, so nobody on the internet can even try to reach them. The tags web and db let firewall rules pick the VMs.

gcloud compute instances create web-vm --zone=us-east1-b --machine-type=e2-micro \
  --subnet=web-subnet --no-address --tags=web --image-family=debian-12 --image-project=debian-cloud 2>&1 | tail -2
gcloud compute instances create db-vm --zone=us-east1-b --machine-type=e2-micro \
  --subnet=db-subnet --no-address --tags=db --image-family=debian-12 --image-project=debian-cloud 2>&1 | tail -2
gcloud compute instances list --format="table(name,zone.basename(),machineType.basename(),networkInterfaces[0].networkIP,networkInterfaces[0].accessConfigs[0].natIP:label=PUBLIC_IP,status)"
NAME    ZONE        MACHINE_TYPE  PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP  STATUS
web-vm  us-east1-b  e2-micro                   10.10.1.2                 RUNNING
NAME   ZONE        MACHINE_TYPE  PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP  STATUS
db-vm  us-east1-b  e2-micro                   10.10.2.2                 RUNNING
NAME    ZONE        MACHINE_TYPE  NETWORK_IP  PUBLIC_IP  STATUS
db-vm   us-east1-b  e2-micro      10.10.2.2              RUNNING
web-vm  us-east1-b  e2-micro      10.10.1.2              RUNNING
Two VMs
Step 5: web-vm 10.10.1.2 and db-vm 10.10.2.2, no public IP

Google gave each VM the first free address of its subnet: .1 is the subnet's gateway, so the VMs got .2.

Step 6: SSH into web-vm through IAP

Why: to run tests from inside the network. --tunnel-through-iap goes through Google instead of a public IP. The grep -v only hides a host-key message some SSH programs print.

gcloud compute ssh web-vm --zone=us-east1-b --tunnel-through-iap --strict-host-key-checking=no \
  --command="hostname; ip -4 -brief addr show ens4; ip route" 2>&1 | grep -v "^Store key\|^Waiting"
web-vm
ens4             UP             10.10.1.2/32 metric 100 
default via 10.10.1.1 dev ens4 proto dhcp src 10.10.1.2 metric 100 
10.10.1.1 dev ens4 proto dhcp scope link src 10.10.1.2 metric 100 
EXTERNAL_IP via 10.10.1.1 dev ens4 proto dhcp src 10.10.1.2 metric 100
Inside web-vm
Step 6: web-vm has 10.10.1.2 and its default route goes via the subnet gateway 10.10.1.1

Inside the VM, the default route goes through 10.10.1.1, the gateway of web-subnet.

Break it: web-vm pings db-vm

gcloud compute ssh web-vm --zone=us-east1-b --tunnel-through-iap --strict-host-key-checking=no \
  --command="ping -c 3 -W 2 10.10.2.2; echo exit code: \$?" 2>&1 | grep -v "^Store key\|^Waiting"
PING 10.10.2.2 (10.10.2.2) 56(84) bytes of data.

--- 10.10.2.2 ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 2036ms

exit code: 1
Ping blocked
100 percent packet loss: no firewall rule allows ICMP into db-vm

100% packet loss. The route exists (same VPC), but the firewall's default "deny all incoming" drops the ping at db-vm's door.

Fix it: allow ping from the web subnet to VMs tagged db

One rule: ICMP (ping) traffic, from 10.10.1.0/24, to VMs with the tag db. Then ping again:

gcloud compute firewall-rules create cbc-allow-icmp-web-to-db --network=cbc-vpc \
  --direction=INGRESS --action=ALLOW --rules=icmp --source-ranges=10.10.1.0/24 --target-tags=db 2>&1 | tail -2
sleep 10
gcloud compute ssh web-vm --zone=us-east1-b --tunnel-through-iap --strict-host-key-checking=no \
  --command="ping -c 3 -W 2 10.10.2.2; echo exit code: \$?" 2>&1 | grep -v "^Store key\|^Waiting"
📝⭐ Recommended by CareerByteCode · Certification examGoogle Analytics Certification (GA4) PracticeTake the examTake the exam →
NAME                      NETWORK  DIRECTION  PRIORITY  ALLOW  DENY  DISABLED
cbc-allow-icmp-web-to-db  cbc-vpc  INGRESS    1000      icmp         False
PING 10.10.2.2 (10.10.2.2) 56(84) bytes of data.
64 bytes from 10.10.2.2: icmp_seq=1 ttl=64 time=1.46 ms
64 bytes from 10.10.2.2: icmp_seq=2 ttl=64 time=0.375 ms
64 bytes from 10.10.2.2: icmp_seq=3 ttl=64 time=0.336 ms

--- 10.10.2.2 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2004ms
rtt min/avg/max/mdev = 0.336/0.722/1.455/0.518 ms
exit code: 0
Ping allowed
One rule later: 3 packets received, about 0.4 ms

0% packet loss, in well under a millisecond: both VMs are in the same zone.

POC: the rule works one way only, and why the internet is out of reach

Firewall rules are about the destination's door. Our rule opens db-vm's door to web-vm. Does it open web-vm's door to db-vm?

gcloud compute ssh db-vm --zone=us-east1-b --tunnel-through-iap --strict-host-key-checking=no \
  --command="ping -c 2 -W 2 10.10.1.2; echo exit code: \$?" 2>&1 | grep -v "^Store key\|^Waiting"
PING 10.10.1.2 (10.10.1.2) 56(84) bytes of data.

--- 10.10.1.2 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1003ms

exit code: 1

No: web-vm has no rule allowing ICMP in. (Reply packets of an allowed connection always get back, because Google Cloud firewalls are stateful; that is why Step 8's replies worked.)

Now the internet. The VPC has a default route to the internet gateway, so try reaching Google from web-vm:

gcloud compute ssh web-vm --zone=us-east1-b --tunnel-through-iap --strict-host-key-checking=no \
  --command="curl -s -m 8 -o /dev/null -w \"%{http_code}\" https://www.google.com; echo \" curl exit code: \$?\"" 2>&1 | grep -v "^Store key\|^Waiting"
000 curl exit code: 28

curl exit code: 28 means "timed out". A VM needs a public IP or a Cloud NAT to use the internet gateway; the route alone is not enough. That is exactly what you want for a database server.

The final firewall rules of the VPC:

gcloud compute firewall-rules list --filter="network:cbc-vpc" --format="table(name,direction,sourceRanges.list(),allowed[].map().firewall_rule().list(),targetTags.list())"
NAME                      DIRECTION  SOURCE_RANGES    ALLOW   TARGET_TAGS
cbc-allow-icmp-web-to-db  INGRESS    10.10.1.0/24     icmp    db
cbc-allow-ssh-iap         INGRESS    35.235.240.0/20  tcp:22
One way, no internet, all rules
db-vm cannot ping web-vm; curl to the internet times out; the two rules of the VPC

Clean up (delete everything)

Why: delete in this order: VMs first, then firewall rules, then subnets, then the VPC (a VPC cannot be deleted while something uses it).

gcloud compute instances delete web-vm db-vm --zone=us-east1-b --quiet 2>&1 | tail -2
gcloud compute firewall-rules delete cbc-allow-ssh-iap cbc-allow-icmp-web-to-db --quiet 2>&1 | tail -2
gcloud compute networks subnets delete web-subnet db-subnet --region=us-east1 --quiet 2>&1 | tail -2
gcloud compute networks delete cbc-vpc --quiet 2>&1 | tail -1
echo "VMs: $(gcloud compute instances list --format="value(name)" | wc -l), firewall rules in cbc-vpc: $(gcloud compute firewall-rules list --filter="network:cbc-vpc" --format="value(name)" | wc -l), networks named cbc-vpc: $(gcloud compute networks list --filter="name=cbc-vpc" --format="value(name)" | wc -l)"
Deleted [https://www.googleapis.com/compute/v1/projects/your-project-id/zones/us-east1-b/instances/web-vm].
Deleted [https://www.googleapis.com/compute/v1/projects/your-project-id/zones/us-east1-b/instances/db-vm].
Deleted [https://www.googleapis.com/compute/v1/projects/your-project-id/global/firewalls/cbc-allow-ssh-iap].
Deleted [https://www.googleapis.com/compute/v1/projects/your-project-id/global/firewalls/cbc-allow-icmp-web-to-db].
Deleted [https://www.googleapis.com/compute/v1/projects/your-project-id/regions/us-east1/subnetworks/web-subnet].
Deleted [https://www.googleapis.com/compute/v1/projects/your-project-id/regions/us-east1/subnetworks/db-subnet].
Deleted [https://www.googleapis.com/compute/v1/projects/your-project-id/global/networks/cbc-vpc].
VMs: 0, firewall rules in cbc-vpc: 0, networks named cbc-vpc: 0
Clean up
0 VMs, 0 rules and 0 cbc-vpc networks left

FAQ

Why not use the "default" network? It is an auto-mode network with wide rules (for example SSH from anywhere in many projects). Fine for a first test, risky for anything real. Plan your own.

Can two VMs in different regions talk privately? Yes, if they are in the same VPC: Google routes the traffic over its own network, with internal IPs.

How do I give private VMs internet access for updates? Add a Cloud NAT to the region (a Cloud Router + NAT config). The VMs still have no public IP, and nobody can connect to them from outside.

What is the difference between a network tag and a service account target? Both pick VMs for a rule. Tags are simple labels; service accounts are harder to change by mistake, so many teams use them for security rules.

Is ping enough to test a database rule? It tests the network path. For a real database also allow its port (for example tcp:5432 for PostgreSQL) from the web subnet only.

What does priority mean on routes and rules? Lower number wins. Subnet routes have priority 0; our rules use the default 1000.

Troubleshooting

You seeWhyFix
100% packet loss between VMsNo ingress rule on the target VMAdd a rule with the right source range and target tag (Fix it step)
SSH hangs or cannot connectNo rule allows 35.235.240.0/20 on tcp:22Run Step 4
curl exit code: 28 from a VMNo public IP and no Cloud NATAdd Cloud NAT, or (for tests only) a public IP
Subnet create fails with an overlap errorTwo subnets in one VPC cannot share addressesPick another range, for example 10.10.3.0/24
Deleting the subnet or VPC fails because it is in useSomething still uses the VPC or subnetDelete VMs, then rules, then subnets, then the VPC
The rule exists but ping still failsThe VM does not have the target taggcloud compute instances describe db-vm --zone=us-east1-b --format="value(tags.items)"

What next

Prepared by the CareerByteCode Team from our tested lab, with AI help for the write-up.

Read next →Google Cloud IAM for Beginners: Roles, Members and Least Privilege⏱ 10 min

⭐ Keep learning with CareerByteCode

Hand-picked to go deeper on this topic
News, guides and updates from the CareerByteCode team
🏅 Contributor writer

The CareerByteCode team writes about what is new on careerbytecode.in: courses, labs, exams, events and the community, which is free to join for influencers and content creators in tech.

Get CareerByteCode Team's next blog by email

One email a week when they publish. Add the weekly Best of ByteBlog too. No spam, unsubscribe with one click.

We email you once to confirm. By subscribing you agree to the privacy policy.

💬 Comments (0)

Top · Newest

Sign in to comment

Related blogs

🧪⭐ Recommended by CareerByteCode · ByteLabs project bundleCloud and DevOps Realtime Starterโ‚น499Build the projects →