Chapters

Egress and Cloud NAT

Chapter 6 made Kadé's VMs reachable for admin work without external IPs. This chapter covers the other direction: how a VM with no external IP reaches the internet, and how to make all of Kadé's outgoing traffic come from one fixed address that a partner can allow-list.

Leaving and reaching privately · chapter 10 of 26 · 12 min read

The core split: with or without an external IP

Builds on10. NAT

How a VM reaches the internet depends entirely on whether it has an external IP:

#The VM has…Path outThe world sees
1An external IPDirect, through 1:1 NAT on its host (chapter 3)The VM's own external IP
2No external IPNone: internal IPs cannot be routed on the internetNothing; it cannot get out
3No external IP and Cloud NATThrough Cloud NATThe NAT IP
kade-vpc · asia-southeast1test-vmhas external IP 34.87.130.4kade-api-1 todayno external IP, no NATkade-api-1 afterno external IP, NAT covers itCloud NAT kade-natNAT IP 34.87.200.7InternetPayGate, apt mirrorssrc 34.87.130.4 (NAT ignored)✕no pathsrc 34.87.200.7
  • Your VPC
  • Allowed traffic and replies

Cloud NAT does nothing for a VM that has its own external IP. Its traffic still leaves as that IP; the NAT is ignored.

Wide by design - scroll it sideways.

The other ways traffic can leave a VPC, for completeness:

#Way outWhat it is forChapter
1Private Google AccessGoogle APIs only (Cloud Storage, Secret Manager, and so on), without the internet9
2A proxy or NAT VM with a tagged routeInspecting or filtering traffic yourself. Usually not worth running4
3Private NATPrivate-to-private translation between networks whose ranges overlap. Not for the internet7
4VPN or InterconnectTraffic to the office or another network15

What Cloud NAT is, and what it is not

Cloud NAT is Google's managed way to give private VMs outbound internet access. Each Cloud NAT setup - its subnets, NAT IPs and port settings - is called a Cloud NAT gateway. Kadé will have one, kade-nat. Despite the name, it has nothing to do with the default-internet-gateway route (chapter 4), although it needs that route to work.

The important part is what it is not.

Not a box

#AWS NAT GatewayCloud NAT
1A real thing that sits in a subnetConfiguration only
2Has a network interface, an IP and a bandwidth limitNo box, no instance, no NAT-device bandwidth limit
3Traffic physically flows through it, and it can failNo single point of failure
4Lives in one availability zone: high availability means one per zoneOne gateway covers every zone in its region
region asia-southeast1kade-router (Cloud Router)holds kade-nat · NAT IP 34.87.200.7settings only: no packets pass heresettings pushed to every hostzone a · physical hostkade-api-1data planeroute → firewall → NATsrc 10.10.1.10 → 34.87.200.7zone b · physical hostkade-api-2data planeroute → firewall → NATsrc 10.10.1.11 → 34.87.200.7src 34.87.200.7InternetPayGate, apt mirrors
  • Run by Google
  • Your VPC
  • Allowed traffic and replies

Translation happens on each VM's host, in the same data plane as routing and the firewall (chapter 1.2). The "gateway" is a set of instructions every host follows, and kade-router is only where those instructions are kept.

Wide by design - scroll it sideways.

Regional, and hosted on a Cloud Router

A Cloud Router is a regional resource in your VPC, and its name is misleading: it never forwards a packet. It belongs to the control plane, and it has two jobs:

  • It speaks BGP. Over a VPN or Interconnect, it swaps routes with the router on the other side (chapter 4, chapter 15).
  • It holds Cloud NAT settings. A Cloud NAT gateway cannot exist on its own. It is always created on a Cloud Router, which is why the command reads routers nats create.

Kadé only needs the second job, so kade-router runs no BGP at all. It exists purely as a home for kade-nat, which is very common. The router comes first, then the NAT on it:

gcloud compute routers create kade-router \  --network=kade-vpc --region=asia-southeast1 gcloud compute routers nats create kade-nat \  --router=kade-router --region=asia-southeast1
The NAT command needs a few more flags (the NAT IP, the subnets, logging). Commands 6 and 7 at the end of the chapter have them in full.

What "regional" means in practice:

  • One gateway, every zone. A gateway serves subnets in its own region and covers every zone in it at once. There is nothing to add for high availability: if zone a fails, kade-api-2's host in zone b keeps translating its own traffic.
  • A second region needs a second gateway. A Cloud Router belongs to one VPC and one region, so each region that needs internet access gets its own router and its own Cloud NAT. Kadé runs only in asia-southeast1, so one is enough.
  • Separate jobs, separate routers. One router could do both jobs, but chapter 15's VPN gets its own, kade-vpn-router. That way, changing or deleting the VPN's BGP setup can never touch internet access.

Outbound only

A one-way door. Replies get back in because Cloud NAT remembers each connection the VM opened. A connection that starts outside matches nothing and is dropped before any firewall rule is checked.

kade-vpc · asia-southeast1kade-api-110.10.1.10no external IPa bad firewall rule0.0.0.0/0 on tcp:22never reachedCloud NATconnection table34.87.200.7:41002↔ 10.10.1.10:51000no entry: droppedpublic internetPayGateapi.paygate.lk:443Anyone elsescanners, SSH botssrc 10.10.1.10src 34.87.200.7dst 34.87.200.7dst 10.10.1.10✕to port 22
  • Run by Google
  • Your VPC
  • Allowed traffic and replies
  • Firewall and access rules

One-way does not mean locked down: the VM can still connect to any address. To limit where it goes, use egress firewall rules (chapter 5.1).

Wide by design - scroll it sideways.

For traffic coming in you need a load balancer (chapter 11) or an external IP, which are different mechanisms entirely.

How it works with the rest of the VPC

#FactWhat it means
1It needs a route to the default internet gatewayDelete the default route and Cloud NAT stops working (chapter 4 section 08)
2Egress firewall rules run firstThey are checked against the VM's internal IP before translation. A deny still blocks the traffic
3It turns on Private Google Access automaticallyFor every subnet range it serves, and it cannot be turned off while NAT covers that range. Traffic to Google APIs never goes through NAT (chapter 9)

What a gateway covers

A Cloud NAT gateway applies to subnet ranges you choose in its region:

#SettingCoversWhen
1All subnets, all rangesEvery primary and secondary range in the region, including subnets added laterSimple setups; the default in the console
2All subnets, primary ranges onlyEvery subnet's primary rangeSecondary ranges should not get internet access
3A list of subnetsOnly the subnets (and ranges) you nameYou want to decide per subnet. Kadé's choice
A subnet range can be covered by only one Cloud NAT gateway.

NAT IPs: automatic or manual

#AutomaticManual
1Who picks the IPsGoogle, from its poolYou, from static external IPs you reserved (chapter 3)
2Can they change?yes Google adds and removes IPs as neededno only you change them
3Number of IPsGrows with demandFixed; you must add more if ports run out (section 05)
4Good forNothing depends on the source IPAn allow-list somewhere depends on it

PayGate's allow-list means Kadé needs manual. The address must be regional, in the same region as the gateway (chapter 3 section 04). When you later add a second NAT IP, tell partners before adding it, because new connections may leave from either address.

Ports: the limit that actually bites

Builds on31. Ports and the 5-tuple

NAT works by giving each outgoing connection its own source port on the NAT IP, so replies can find their way back. That makes ports the real capacity of a gateway:

#NumberMeaning
164,512 ports per NAT IP65,536 minus the 1,024 well-known ports
264 ports per VM by defaultEach VM reserves a block of source ports (the "minimum ports per VM" setting)
364,512 ÷ 64 = 1,008 VMs per NAT IPHow many VMs one IP can serve at the default
464 connections to one destinationThe catch: a port can be reused for different destinations, but one VM can have only as many connections open to the same IP and port as it has reserved ports

Row 4 is what hurts in practice. If kade-api-1 opens more than 64 connections to api.paygate.lk:443 at the same time, connection 65 is dropped, and the NAT logs show OUT_OF_RESOURCES. The fundamentals course (ch 10) mentioned this error; this is where it comes from. Closed connections also hold their port for a while (TIME_WAIT, section 06), so a burst of short connections can use up ports faster than you expect.

See it: two VMs, two destinations

kade-api-1 opens connections to

PayGate3
apt mirror0

kade-api-2 opens connections to

PayGate0
apt mirror0
Cloud NAT kade-nat · 34.87.200.7 · 8 source ports per VMkade-api-110.10.1.10ports 1024-103110241025102610271028102910301031to PayGate :4433 of 8to apt mirror :800 of 83 connections open · 3 of 8 ports busykade-api-210.10.1.11ports 1032-103910321033103410351036103710381039to PayGate :4430 of 8to apt mirror :800 of 80 connections open · 0 of 8 ports busy

3 connections open on 3 ports. Each connection to the same destination needs its own port.

Drawn with 8 ports per VM so every port fits. The default is 64, and the rule is the same: a row is one destination, a column is one port, and a port can be used once per row.

#FixEffect
1Reuse connections in the app (HTTP keep-alive, connection pooling)Fewer connections, fewer ports. The best fix, and free
2Raise the minimum ports per VMMore connections per destination, fewer VMs per IP
3Turn on dynamic port allocationVMs start small and get more ports when busy, up to a maximum you set
4Add NAT IPsMore ports in total. Tell allow-list owners first

Try it: will the ports last?

NAT IPs
Min ports per VM
Total NAT ports
1 × 64,512 = 64,512
Most VMs at this minimum
1,008
Ports reserved now
192
Max open to one destination, per VM
64
Sustained new connections per second to one destination
about 0.53, because each closed port waits 120 s (TIME_WAIT) before reuse

OUT_OF_RESOURCES: each VM has 64 ports, so only 64 connections can be open to PayGate at once. Connections 65 to 150 are dropped. Pool connections, raise the minimum, or turn on dynamic port allocation.

Timeouts

Cloud NAT forgets a connection after it has been idle for a while. The defaults:

#TimeoutDefaultWhat it means for Kadé
1TCP established, idle1,200 s (20 min)A connection with no traffic for 20 minutes is silently dropped. Long-lived connections need keep-alives shorter than that
2TCP transitory (opening or closing)30 sHalf-open connections are cleared quickly
3TCP TIME_WAIT120 sA closed connection's port stays reserved this long before it can be used for the same destination again
4UDP30 sDNS and other short UDP exchanges
5ICMP30 sPing
All of these can be changed per gateway. Lowering TIME_WAIT is one way to free ports faster for bursty traffic.

Scenarios

Each tab is one trip on the same map of Kadé. The three boxes in the middle are the checks the host makes, in order: route, firewall, then NAT. Each scenario stops at a different one, or turns off before the NAT.

What if
kade-vpc · asia-southeast1kade-api-110.10.1.10no external IPon the VM's host, in order1 · route0.0.0.0/02 · firewallallowed3 · Cloud NAT34.87.200.7✓✓✓public internetPayGateallows 34.87.200.7sees 34.87.200.7✓Any other sitenot on Kadé's listGoogle's networkGoogle APIsCloud Storage

Works: PayGate sees 34.87.200.7, which is on its list

PayGate sees one address, 34.87.200.7, whichever VM made the call. The same holds for kade-api-2, kade-worker and Cloud Run (chapter 10), as long as each is covered by the gateway and has no external IP.

Show as config
PayGate's allow-list: 34.87.200.7/32
kade-nat: manual IP kade-nat-ip (34.87.200.7), subnets sn-app, sn-data

To keep external IPs off for good (chapter 17):
  constraints/compute.vmExternalIpAccess = deny all

Private NAT, briefly

Cloud NAT has a second type. Private NAT translates between two private networks, usually because their ranges overlap and cannot be renumbered, for example two VPCs joined through Network Connectivity Center, or a VPC and an on-premises network over VPN. It takes its addresses from a subnet with purpose PRIVATE_NAT (chapter 2 section 06), and it never gives internet access. Kadé's address plan has no overlaps, so it does not need it.

Cost, logs and monitoring

#Where to lookWhat it shows
1NAT logging, errors onlyEvery dropped connection with its reason, such as OUT_OF_RESOURCES. Cheap and worth having on
2NAT logging, translationsEvery connection that was translated. Useful for audits, but more log volume
3Monitoring metricsdropped_sent_packets_count by reason, and allocated ports per VM
4gcloud compute routers get-nat-mapping-infoWhich NAT IP and port ranges each VM has right now
Chapter 16 covers reading these logs.

A route, a rule, an address: the full picture

Builds on5. The default gateway10. NAT

With Cloud NAT in place, every piece of the question "will this packet get through?" has been covered. Three separate things decide it, and all three must line up:

  1. A route says which way. The VPC route table picks the most specific match, and 0.0.0.0/0 is used only when nothing more specific matches (chapter 4).
  2. A firewall rule says whether it is allowed. This applies even between two VMs in the same subnet. Outgoing is allowed and incoming is denied, unless a rule says otherwise (chapter 5.1).
  3. A public address is needed to talk to the internet. An external IP works both ways (chapter 3). Cloud NAT works outwards only.
1 · Routewhich way2 · Firewall rulewhether it is allowed3 · Public addressto use the internetkade-api-1 → kade-db10.10.1.10 → 10.10.2.510.10.2.0/24ingress rulestays in the VPCkade-api-1 → PayGatebefore Cloud NAT0.0.0.0/0egress allowednone: droppedkade-api-1 → PayGatewith Cloud NAT0.0.0.0/0egress allowedNAT IP 34.87.200.7kade-db → Cloud StoragePrivate Google Access on0.0.0.0/0egress allowedstays in Google
  • Route
  • Traffic that gets through
  • Firewall rule

Every trip passes the same three checks, in this order. A trip that stays inside the VPC, or inside Google, never needs a public address. Before this chapter, kade-api-1's calls to PayGate had a route and an allowed firewall, and stopped at the third check.

Wide by design - scroll it sideways.

Out of a VM:

#From → toRoute that matchesAlso needsSource the receiver sees
1VM → VM, same subnetkade-api-1 → kade-api-2Subnet route 10.10.1.0/24An ingress rule (ch 5.1)The sender's internal IP, 10.10.1.10
2VM → VM, other subnet, same VPCkade-api-1 → kade-dbSubnet route 10.10.2.0/24An ingress ruleThe sender's internal IP, 10.10.1.10
3VM → VM in another VPCNone, by defaultPeering or a VPN (ch 14, 15)The sender's internal IP, with peering
4VM with an external IP → internet0.0.0.0/0Nothing moreThe VM's external IP
5VM without an external IP → internetkade-api-1 → PayGate0.0.0.0/0Cloud NAT (this chapter)The NAT IP, 34.87.200.7
6VM without an external IP → Google APIs0.0.0.0/0Private Google Access on the subnet (ch 9)It stays inside Google
7VM → another VM's external IP0.0.0.0/0The sender needs an external IP or NATThe sender's public IP. Avoid this (ch 3)

Into a VM, from the internet:

#TargetReachable?WhySource the VM sees
1A VM with an external IP, on port 443Only if an ingress rule allows itIncoming is denied by defaultThe client's public IP
2A VM with no external IP, such as kade-dbNever directlyThere is no public address to send to-
3A VM with only Cloud NATNever directlyCloud NAT is outgoing only-

To reach a VM with no external IP from outside, put something in front that has one. For websites and APIs that is a load balancer: the public IP lives on the load balancer, which forwards to the VMs on their internal IPs (chapter 11). Behind a proxy load balancer such as Kadé's, the VM sees the load balancer's address and finds the client's in a header (chapter 12.1). For SSH and admin it is IAP TCP forwarding, which needs only a firewall rule for Google's IAP range 35.235.240.0/20 (chapter 6.1).

Back to Kadé

Commands in this chapter

Commands 1 to 4 are read-only. Commands 5 to 7 change the project.

See the outgoing IP from inside a VM

  • What it shows: The source address the internet sees for this VM.
  • What to look for: 34.87.200.7. A different address means the VM has its own external IP (section 07, tab A). A timeout means no NAT covers its subnet.
curl -s ifconfig.me

Describe the NAT gateway

  • What it shows: Which subnets it covers, IP allocation mode, NAT IPs, port settings, timeouts and logging.
  • What to look for: natIpAllocateOption: MANUAL_ONLY, the expected subnets, and minPortsPerVm.
gcloud compute routers nats describe kade-nat \  --router=kade-router --region=asia-southeast1

See which ports each VM holds

  • What it shows: For every VM using the gateway, its NAT IP and port ranges.
  • What to look for: VMs with far more ports than others (busy under dynamic allocation), or VMs missing from the list (not covered).
gcloud compute routers get-nat-mapping-info kade-router --region=asia-southeast1

Find NAT drops in the logs

  • What it shows: Connections Cloud NAT dropped in the last day, with the reason.
  • What to look for: OUT_OF_RESOURCES (ports ran out, section 05). Needs error logging on.
gcloud logging read \  'resource.type="nat_gateway" AND jsonPayload.allocation_status="DROPPED"' \  --freshness=1d --limit=20

Reserve the NAT IP (changes the project)

  • What it shows: Creates the regional static address for the gateway.
  • What to look for: The address in gcloud compute addresses list, status RESERVED until the gateway uses it. Send this address to PayGate now.
gcloud compute addresses create kade-nat-ip --region=asia-southeast1

Create the Cloud Router (changes the project)

  • What it shows: A regional Cloud Router that only hosts the NAT settings. No BGP sessions.
  • What to look for: It appears in gcloud compute routers list.
gcloud compute routers create kade-router \  --network=kade-vpc --region=asia-southeast1

Create the NAT gateway (changes the project)

  • What it shows: Cloud NAT with the fixed IP, for two named subnets, with error logging.
  • What to look for: Command 1 on kade-api-1 prints 34.87.200.7 within a minute or two.
gcloud compute routers nats create kade-nat \  --router=kade-router --region=asia-southeast1 \  --nat-external-ip-pool=kade-nat-ip \  --nat-custom-subnet-ip-ranges=sn-app,sn-data \  --enable-logging --log-filter=ERRORS_ONLY

Spotted a mistake, or something unclear? Suggest an edit on GitHub

See it broken

Harbour is a platform built wrong on purpose. This defect is this chapter's idea, left undone: what it breaks, how you would find it, and the change that closes it.

  1. D3b