When deploying services on Cloud Run, the default behaviour is that the backend IP address (that is, where requests to external endpoints come from within your app), is assigned from a dynamic IP address pool.
Therefore, for cases that require IP whitelisting, you need to configure the Cloud Run instance to use a static backend IP, which can be achieved through the magic✨ (read: networking capabilities) of VPC Connector.
Note that we are referring to the outbound IP here, not the inbound IP which instead is how traffic gets to our Cloud Run instance and can be configured via a load balancer.
Check out the Google Cloud docs here for static outbound IP addresses
How to Configure a Static Outbound IP?
Step 1: Create a Router
gcloud compute routers create my-router --network=default --region=my-region
Creating router [my-router]...done.
NAME REGION NETWORK
my-router my-region default
Step 2: Reserve a Static IP
gcloud compute addresses create my-ip --region=my-region
Created [https://www.googleapis.com/compute/v1/projects/my-project/regions/my-region/addresses/my-ip].
Optional Step: View Existing Subnets
gcloud compute networks subnets list --network=default --filter="region:(my-region)"
NAME REGION NETWORK RANGE STACK_TYPE IPV6_ACCESS_TYPE INTERNAL_IPV6_PREFIX EXTERNAL_IPV6_PREFIX
default my-region default 0.0.0.0/00 IPV4_ONLY
my-other-subnet my-region default 0.0.0.0/00 IPV4_ONLY
In reality, your existing subnets will have actual IP ranges. Take note of this when choosing your new range so it is not equal to an existing one.
Step 3: Create a new Subnet
gcloud compute networks subnets create my-subnet --netwo
rk=default --range=00.0.0.0/01--region=my-region
Created [https://www.googleapis.com/compute/v1/projects/my-project/regions/my-region/subnetworks/my-subnet].
NAME REGION NETWORK RANGE STACK_TYPE IPV6_ACCESS_TYPE INTERNAL_IPV6_PREFIX EXTERNAL_IPV6_PREFIX
my-subnet my-region default 10.0.0.0/24 IPV4_ONLY
Step 4: Create a Cloud NAT Gateway
gcloud compute routers nats create my-nat \
--router=my-router \
--region=my-region \
--nat-custom-subnet-ip-ranges=my-subnet \
--nat-external-ip-pool=my-ip
Use the names you configured in the previous steps here.
Creating NAT [my-nat] in router [my-router]...done.
Step 5: Set the Networking on your Cloud Run Revision
Important - If it's not working, confirm that it is set to route all traffic to the VPC, not just route only requests to private IPs to the VPC -- use case for private traffic is between google services eg. static IP for Cloud SQL in API endpoint cloud run revisions
Step 6: See the Static Outbound IP from Cloud NAT
And all done! To test all is working as intended, you can make an API request to services such as GET https://api.ipify.org?format=json
from within your Cloud Run application.
Top comments (0)