Static IPs for Google Cloud Functions and Cloud Run

QuotaGuard Engineering
October 26, 2026
•
5 min read
Pattern

Google Cloud Functions and Cloud Run share the same outbound IP problem as every other serverless platform: by default, your traffic exits from a pool of shared, rotating IP addresses. If a partner API, database, or firewall needs a whitelisted IP, you don't have a fixed one to give them until you configure a static outbound route.

How GCP Handles Outbound IPs

Cloud Functions (both 1st and 2nd gen) egress from a shared pool of Google-owned IPs by default. The specific IP used for any given request is unpredictable. A project's default egress is not a dedicated, stable address set to hand to a partner.

Cloud Run is the same story by default. Containers run on shared infrastructure, and outbound traffic exits from Google's dynamic pool. You can't rely on a fixed source IP without configuring the outbound path. Google documents this in its static outbound IP guide.

This is fine for calling public APIs that authenticate with API keys. It's a problem when the service on the other end needs to know your IP address.

Which Functions generation and deployment command are you using?

Google now calls the current product Cloud Run functions, formerly Cloud Functions (2nd gen). Check the resource's generation and management API before copying a deployment command. The request-level proxy patterns below apply to the HTTP clients shown; trigger configuration is a separate deployment choice.

Existing or new workloadDeployment choiceWhat changes here
New Cloud Run functiongcloud run deploy --source --function --base-imageGoogle's recommended management API; use the current deployment example below.
Function managed through Cloud Functions v2 APIgcloud functions deploy --gen2Keep this workflow for compatibility; a Cloud Run Admin API-created function cannot be managed through the Functions API.
Existing 1st gen functiongcloud functions deploy --no-gen2Keep its existing trigger and region. Select a runtime that supports 1st gen; do not apply the current-generation example unchanged.

See Google's generation and API comparison. This guide uses python313 and nodejs22 for its deployment examples. Python 3.13 is current-generation only; Python 3.12 and Node.js 22 are listed for both generations. Newer runtime choices are also available; check the runtime support schedule for your generation and planned upgrade date.

The GCP-Native Fix (And What It Costs)

Google's recommended approach for static outbound IPs involves three components:

Serverless VPC Access Connector or Direct VPC egress. This connects the workload to a VPC network. A connector uses dedicated compute instances and has its own charges. For current Cloud Run functions and services, Google recommends Direct VPC egress where suitable, so a connector is not always required. Route all outbound traffic into the VPC when public internet calls must use NAT; private-ranges-only routing does not do that.

Cloud NAT Gateway. Once public outbound traffic is routed through the VPC, Cloud NAT can give it a known source address. Its public NAT gateway charge depends on usage and instance count, plus processed data and external-address charges; $0.044/hour is not a universal base price.

Static IP reservation. Reserve external addresses and manually assign them to NAT for a predetermined allowlist. Addresses used by Cloud NAT are billed; they are not free merely because they are in use.

Total cost depends on connector use, scale, data processed, addresses and network transfer. Calculate the actual workload with Google's current Cloud NAT pricing instead of assuming a $40–200 monthly range.

For teams already running a VPC with other GCP services, adding Cloud NAT to the existing infrastructure is reasonable. For a team on Cloud Functions that just needs one API call to go through a known IP, it's a lot of infrastructure.

For the full network-path comparison and startup troubleshooting, use our Cloud Run static IP and NAT guide. The rest of this post focuses on configuring and verifying function clients.

The Proxy Approach

QuotaGuard gives you two static IPs. You route outbound traffic through the proxy. No new VPC connector or NAT gateway is required for this proxy approach when your function can reach the external proxy. Configure the specific HTTP client, and allowlist both assigned addresses from your QuotaGuard dashboard. Standard plans use a shared static IP pair; dedicated plans are available.

Store the proxy URL as a secret

Copy the exact QuotaGuard Static outbound connection URL from your subscription setup. Its credentials authenticate to the proxy, not the partner API. Keep the http:// proxy scheme supplied by the dashboard even for an HTTPS destination: these clients use CONNECT for HTTPS. Do not paste the credential into source, build arguments, screenshots or logs.

The following Bash setup is for a project where you can enable APIs, create a runtime service account and manage the secret. Use your existing dedicated runtime account instead if you have one. Set your real project and region; use a current Google Cloud CLI. Source deployments also require the deployer and build-service-account permissions in Google's deployment prerequisites.

PROJECT_ID='your-project-id'
REGION='us-central1'
RUNTIME_SA="qg-function@${PROJECT_ID}.iam.gserviceaccount.com"

gcloud services enable run.googleapis.com cloudbuild.googleapis.com \
  artifactregistry.googleapis.com logging.googleapis.com \
  secretmanager.googleapis.com --project="$PROJECT_ID"

# Skip creation if this dedicated runtime account already exists.
gcloud iam service-accounts create qg-function --project="$PROJECT_ID"

# Create once. For rotation, add a version to the existing secret instead.
gcloud secrets create quotaguard-static-url \
  --replication-policy=automatic --project="$PROJECT_ID"

# Bash: hidden input; do not enable shell tracing (set -x).
set +x
read -r -s -p 'QuotaGuard Static connection URL: ' QG_PROXY_SECRET
printf '\n'
printf '%s' "$QG_PROXY_SECRET" | gcloud secrets versions add \
  quotaguard-static-url --data-file=- --project="$PROJECT_ID"
unset QG_PROXY_SECRET

gcloud secrets add-iam-policy-binding quotaguard-static-url \
  --member="serviceAccount:$RUNTIME_SA" \
  --role=roles/secretmanager.secretAccessor --project="$PROJECT_ID"

Bind a numeric secret version at deployment, such as 1 for a newly created secret. On rotation, use the version reported when adding the new value and redeploy. Secret access belongs to the runtime account; build permissions belong to the build identity. Google's secret configuration guide explains startup resolution and version pinning.

The examples below keep TARGET_URL fixed in server-side code. Set VERIFY_IP=true only during verification to call the IP checker through the same client. Once it passes, replace the partner placeholder with your real HTTPS endpoint, add that API's required authentication, and redeploy with VERIFY_IP=false. Do not accept a target URL from an incoming request.

Cloud Functions (Python)

import os
import requests
import functions_framework

proxy_url = os.environ["QUOTAGUARDSTATIC_URL"]
if not proxy_url:
    raise RuntimeError("Missing proxy configuration")
verify_ip = os.environ.get("VERIFY_IP") == "true"
TARGET_URL = ("https://ip.quotaguard.com" if verify_ip
              else "https://api.partner.com/data")

@functions_framework.http
def my_function(request):
    proxies = {"http": proxy_url, "https": proxy_url}
    try:
        with requests.Session() as client:
            client.trust_env = False
            response = client.get(
                TARGET_URL, proxies=proxies, timeout=(5, 20),
                allow_redirects=False
            )
            if not 200 <= response.status_code < 300:
                return {"error": "Upstream rejected request"}, 502
            if verify_ip:
                return response.text.strip(), 200, {
                    "Content-Type": "text/plain; charset=utf-8"
                }
            return response.json()
    except (requests.RequestException, ValueError):
        return {"error": "Upstream request failed"}, 502

Save this as qg-python/main.py. Set QUOTAGUARDSTATIC_URL through the secret binding below. The proxy dictionary explicitly routes both HTTP and HTTPS; trust_env=False prevents ambient proxy settings from choosing another path. Add qg-python/requirements.txt:

functions-framework>=3.10,<4
requests>=2.32,<3

For local setup, create a virtual environment and run python3 -m pip install -r qg-python/requirements.txt. Requests uses separate connect/read timeouts here; the read timeout is not an overall wall-clock deadline. Requests proxy documentation.

Cloud Functions (Node.js)

const functions = require('@google-cloud/functions-framework');
const fetch = require('node-fetch'); // Explicit node-fetch v2, not global fetch
const { HttpsProxyAgent } = require('https-proxy-agent');

const proxyUrl = process.env.QUOTAGUARDSTATIC_URL;
if (!proxyUrl) throw new Error('Missing proxy configuration');
const agent = new HttpsProxyAgent(proxyUrl);
const verifyIp = process.env.VERIFY_IP === 'true';
const TARGET_URL = verifyIp
  ? 'https://ip.quotaguard.com' : 'https://api.partner.com/data';

functions.http('myFunction', async (req, res) => {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 25000);
  try {
    const response = await fetch(TARGET_URL, {
      agent, signal: controller.signal, redirect: 'error'
    });
    if (!response.ok) {
      res.status(502).json({ error: 'Upstream rejected request' });
      return;
    }
    if (verifyIp) res.type('text/plain').send((await response.text()).trim());
    else res.json(await response.json());
  } catch {
    res.status(502).json({ error: 'Upstream request failed' });
  } finally {
    clearTimeout(timer);
  }
});

Save this as qg-node/index.js and use the following qg-node/package.json. Run npm install --prefix qg-node and retain the resulting lockfile for deployments.

{
  "name": "qg-function-example",
  "version": "1.0.0",
  "private": true,
  "engines": { "node": "22.x" },
  "scripts": { "start": "functions-framework --target=myFunction" },
  "dependencies": {
    "@google-cloud/functions-framework": "^3.4.0",
    "https-proxy-agent": "^7.0.6",
    "node-fetch": "2.7.0"
  }
}

Why the explicit import? node-fetch accepts a Node HTTP agent; native Node.js fetch uses an Undici-compatible dispatcher. Passing { agent } to the global fetch does not configure this proxy. See node-fetch v2's agent option and Node's dispatcher documentation. This example intentionally uses the imported client throughout.

Go: explicit proxy configuration for an HTTPS request

For a Go function, put this helper in the same package as your existing handler and call CallPartner(r.Context()). It is a request helper, not a complete Functions Framework entry point. It uses only Go's standard library and selects the proxy explicitly instead of relying on HTTP_PROXY inheritance.

package function

import (
    "context"
    "errors"
    "io"
    "net/http"
    "net/url"
    "os"
    "time"
)

func CallPartner(ctx context.Context) ([]byte, error) {
    proxyURL, err := url.Parse(os.Getenv("QUOTAGUARDSTATIC_URL"))
    if err != nil || proxyURL.Scheme != "http" || proxyURL.Host == "" {
        return nil, errors.New("invalid Static HTTP proxy configuration")
    }
    transport := http.DefaultTransport.(*http.Transport).Clone()
    transport.Proxy = http.ProxyURL(proxyURL)
    defer transport.CloseIdleConnections()
    client := &http.Client{
        Transport: transport, Timeout: 25 * time.Second,
        CheckRedirect: func(*http.Request, []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    target := "https://api.partner.com/data"
    if os.Getenv("VERIFY_IP") == "true" {
        target = "https://ip.quotaguard.com"
    }
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
    if err != nil { return nil, errors.New("invalid target") }
    resp, err := client.Do(req)
    if err != nil { return nil, errors.New("upstream request failed") }
    defer resp.Body.Close()
    if resp.StatusCode < 200 || resp.StatusCode >= 300 {
        return nil, errors.New("upstream rejected request")
    }
    body, err := io.ReadAll(io.LimitReader(resp.Body, (1 << 20) + 1))
    if err != nil { return nil, errors.New("response read failed") }
    if len(body) > 1 << 20 { return nil, errors.New("response exceeds 1 MiB") }
    return body, nil
}

Write returned bytes to your authorized caller, handle errors without returning credentials, and add partner authentication to req as required. This helper rejects responses larger than 1 MiB; adjust the bound for your real payloads. See Go's HTTP transport reference.

Deploy Python or Node.js as a current Cloud Run function

Choose one source directory created above, and run this from its parent directory after the secret setup. The first deployment calls only the IP checker. Your invoking identity needs roles/run.invoker on the service; keep the test service authenticated.

SOURCE_DIR='./qg-python'
ENTRY_POINT='my_function'
BASE_IMAGE='python313'
# For Node.js instead:
# SOURCE_DIR='./qg-node'; ENTRY_POINT='myFunction'; BASE_IMAGE='nodejs22'
SECRET_VERSION='1'  # Replace with your actual numeric version.

gcloud run deploy qg-proxy-check --source="$SOURCE_DIR" \
  --function="$ENTRY_POINT" --base-image="$BASE_IMAGE" \
  --service-account="$RUNTIME_SA" \
  --update-secrets="QUOTAGUARDSTATIC_URL=quotaguard-static-url:$SECRET_VERSION" \
  --update-env-vars=VERIFY_IP=true --timeout=60 \
  --no-allow-unauthenticated --region="$REGION" --project="$PROJECT_ID"

For an existing Cloud Functions v2 API workflow, use this alternative with the same Python source, runtime account and secret. It needs the Cloud Functions API and its Functions deployment permissions in addition to build prerequisites. Preserve your actual function name and trigger when updating an existing workload.

gcloud services enable cloudfunctions.googleapis.com --project="$PROJECT_ID"
gcloud functions deploy qg-proxy-check-v2 --gen2 \
  --runtime=python313 --source=./qg-python --entry-point=my_function \
  --trigger-http --service-account="$RUNTIME_SA" \
  --update-secrets="QUOTAGUARDSTATIC_URL=quotaguard-static-url:$SECRET_VERSION" \
  --update-env-vars=VERIFY_IP=true --timeout=60 \
  --no-allow-unauthenticated --region="$REGION" --project="$PROJECT_ID"

For Node.js on that v2 workflow, substitute --runtime=nodejs22 --source=./qg-node --entry-point=myFunction. HTTP examples are used here so you can inspect the response. For a Pub/Sub or Eventarc function, use the same configured outbound client inside your event handler, retain its trigger, and await the request before returning; use idempotency controls before retrying writes. Functions deploy flags.

Cloud Run

Cloud Run works the same way. Set the environment variable in your container configuration and use it in your HTTP client. Since Cloud Run runs containers, you have full control over your runtime and dependencies.

import os
import requests
from flask import Flask

app = Flask(__name__)
proxy_url = os.environ["QUOTAGUARDSTATIC_URL"]
if not proxy_url:
    raise RuntimeError("Missing proxy configuration")

@app.route("/process")
def process():
    proxies = {"http": proxy_url, "https": proxy_url}
    try:
        with requests.Session() as client:
            client.trust_env = False
            response = client.get(
                "https://api.partner.com/data", proxies=proxies,
                timeout=(5, 20), allow_redirects=False
            )
            if not 200 <= response.status_code < 300:
                return {"error": "Upstream rejected request"}, 502
            return response.json()
    except (requests.RequestException, ValueError):
        return {"error": "Upstream request failed"}, 502

Save as app.py in your container project and install Flask, requests and gunicorn. Serve it with gunicorn --bind 0.0.0.0:$PORT app:app so Cloud Run can reach the injected port. Bind the same Secret Manager value to the service. For container deployment and network-path details, continue with the Cloud Run guide.

TCP Connections from Cloud Run

Cloud Run can also use QGTunnel for non-HTTP connections (databases, SFTP). Add the QGTunnel binary and its supporting files to your Linux container image, configure the destination mapping, and wrap your application startup command. For example, with the Flask app above:

# Download into the application directory; retain bin/ and vendor/ files.
RUN curl --fail --show-error --silent --location \
    https://s3.amazonaws.com/quotaguard/qgtunnel-latest.tar.gz \
    --output /tmp/qgtunnel.tar.gz \
    && tar xzf /tmp/qgtunnel.tar.gz -C /app \
    && rm /tmp/qgtunnel.tar.gz

WORKDIR /app
# PORT is expanded by the shell; gunicorn serves app:app.
CMD ["sh", "-c", "exec bin/qgtunnel gunicorn --bind 0.0.0.0:${PORT:-8080} app:app"]

Set QUOTAGUARDSTATIC_URL through the service's secret binding. In the dashboard, configure a tunnel for the real destination hostname and port, then supply the downloaded .qgtunnel configuration securely at runtime in the application working directory. QGTunnel opens local sockets that route TCP traffic through static IPs. Transparent mode also requires the bundled vendor/nss_wrapper files and compatible hostname resolution; verify your driver and TLS hostname behavior before assuming the connection string can stay unchanged. A startup wrapper alone does not define a database route. See the QGTunnel setup and troubleshooting instructions. Review and pin the downloaded artifact for a production build.

For managed function-source deployments, the QGTunnel startup-wrapper workflow above is not a drop-in configuration. For TCP from a function, use a client that explicitly supports the assigned SOCKS5 endpoint and authentication, or package the workload as a Cloud Run container when you need to control startup. An HTTP proxies dictionary does not route a native database driver or SFTP client. Confirm the driver's actual proxy support and keep destination TLS verification enabled.

Selective Proxying

Not all outbound calls need a static IP. Calls to Google's own APIs, public SaaS APIs, and services whose policies require only API credentials can go directly. Some APIs require both credentials and an IP allowlist; check the target's actual policy.

Route only the calls that hit firewalled endpoints through the proxy:

import os
import requests

proxy_url = os.environ["QUOTAGUARDSTATIC_URL"]
if not proxy_url:
    raise RuntimeError("Missing proxy configuration")

def call_api(url, needs_static_ip=False):
    proxies = {"http": proxy_url, "https": proxy_url} if needs_static_ip else {}
    with requests.Session() as client:
        client.trust_env = False  # Direct branch ignores ambient proxy variables.
        response = client.get(
            url, proxies=proxies, timeout=(5, 20), allow_redirects=False
        )
        if not 200 <= response.status_code < 300:
            raise RuntimeError("Upstream rejected request")
        return response

# Direct - no IP restriction; use an object you are authorized to read.
google_response = call_api('https://storage.googleapis.com/my-bucket/data.json')

# Through proxy - partner requires whitelisted IP.
partner_response = call_api('https://api.partner.com/data', needs_static_ip=True)

Verify the deployed IP and the actual partner request

For a scheduled CRM sync, an IP check proves the configured request reaches QuotaGuard; a harmless CRM read then proves that the real client, credentials and allowlist work together. For a webhook handler, test the partner call inside the handler rather than checking a separate script on your laptop.

  1. Ask the destination owner to allowlist both assigned QuotaGuard IPv4 addresses. Use your dashboard's pair, not the proxy hostname's DNS addresses or a single observed result.
  2. Invoke the deployed function with VERIFY_IP=true. Use the commands below for the current Cloud Run deployment.
  3. Compare the returned address with the assigned pair. Repeated requests may show the same address; this does not prove both paths or failover have been tested.
  4. Replace https://api.partner.com/data in your server-side source with a harmless real endpoint and add the partner's authentication. Rerun the same deploy command with --update-env-vars=VERIFY_IP=false. Invoke again and inspect the expected response plus the destination's observed source IP or access log, where available.
  5. Repeat from each deployed region/revision and each production SDK that makes protected requests. The IP checker alone does not prove that a different SDK or background worker uses the proxy.
SERVICE_URL="$(gcloud run services describe qg-proxy-check \
  --region="$REGION" --project="$PROJECT_ID" --format='value(status.url)')"
curl --fail-with-body --silent --show-error \
  --header "Authorization: Bearer $(gcloud auth print-identity-token)" \
  "$SERVICE_URL"

For the v2 compatibility example, obtain its HTTPS endpoint with gcloud functions describe qg-proxy-check-v2 --gen2 --region="$REGION" --project="$PROJECT_ID" --format='value(serviceConfig.uri)', then use that URL in the authenticated curl call. A caller permission failure occurs before the outbound client runs. Use your organization's approved invocation identity; do not make the function public to debug egress.

For an allowlist comparison in a sandbox, run the same harmless target read directly and through the proxy with the same credentials and payload. Confirm an explicit IP-policy rejection on the direct route and success on the proxied route. A generic 401/403 or a timeout is not sufficient evidence of an IP restriction. No infrastructure changes or failover exercises are needed for that first check.

Common function proxy errors

SymptomCheck and next step
The function itself returns 401/403Check the invocation identity, service URL and Invoker role first. If the handler never ran, changing proxy settings cannot fix the caller's IAM permission.
Revision fails to start or secret access is deniedCheck the numeric secret version and Secret Accessor permission for the deployed runtime account. Confirm the correct entry point and dependencies. Do not expose the secret in logs.
IP checker still shows a Google addressCheck the client that sent the request, current revision and environment binding. In Node.js, verify the explicit node-fetch import; global fetch ignores HttpsProxyAgent's agent option. Inspect SDK-specific proxy settings separately.
407 Proxy Authentication RequiredUse the exact outbound connection URL and product endpoint from the dashboard. Check for truncation, extra whitespace or a stale secret version. Keep proxy credentials separate from the partner Authorization header.
Partner 401/403 through the correct IPVerify both assigned IPs, API token scopes and the target environment. An allowlist does not replace API authentication. If a vendor provides request IDs, use those to correlate its access logs.
DNS failure, connection timeout or TLS errorCheck proxy host/port reachability, existing all-traffic VPC routing, firewall policy and destination status. A proxy cannot repair a VPC route that cannot reach it. Keep certificate verification enabled; use the Cloud Run guide for native egress/startup diagnosis.
Redirect or non-JSON responseThese examples reject redirects and expect JSON in partner mode. Confirm the exact endpoint, status and content type. Deliberately configure additional approved hosts if the vendor redirects; do not silently change network paths.
Works at low traffic, fails during burstsBound timeouts and concurrency, reuse clients where thread-safe, and check partner/proxy capacity. Retry transient errors with backoff only when the operation is idempotent or protected by an idempotency key.

The sample handlers return a sanitized 502 for upstream failures. For diagnosis, record safe status categories and correlation IDs internally; avoid full exception objects, credential-bearing URLs, authorization headers or sensitive response bodies. Never fall back to direct egress after a protected-route proxy error.

Cost Comparison

GCP VPC egress + Cloud NAT: cost depends on the chosen egress path, NAT usage, processed bytes, addresses and transfer. Requires VPC configuration, IAM permissions and ongoing infrastructure management. Use the native pricing link above for your workload rather than a fixed monthly estimate.

QuotaGuard Static: starts at $19/month, with two static IPs and managed failover. Update your HTTP client and secret binding without operating new NAT infrastructure. Compare included request and bandwidth allowances with your workload on the current pricing page; Google compute, build, secret and network charges remain separate.

For teams that need a VPC for other reasons (connecting to Cloud SQL, Memorystore, or other VPC-networked resources), the native approach makes sense. For teams that just need outbound static IPs for a few proxy-capable API calls, the proxy can be simpler to operate. Compare actual usage and existing infrastructure before deciding on cost.

Getting Started

Sign up for QuotaGuard Static. Retrieve your outbound connection URL and both assigned IPs in the setup guide, bind the secret, and configure the client that makes your protected calls. Test at https://ip.quotaguard.com from the deployed function, then verify the real destination as described above.

If your security review requires TLS on the connection to the proxy as well as TLS to the HTTPS destination, evaluate QuotaGuard Shield, starting at $29/month, with its supported secure connection methods. Static tunnels HTTPS without decrypting the destination payload, but its HTTP proxy hop is not itself TLS-encrypted. Encryption alone does not establish HIPAA or PCI-DSS compliance; confirm the required configuration and agreements with QuotaGuard. See the documented outbound data flow.

Start with the QuotaGuard Static plan that fits your traffic, and use the language and platform documentation for the client you actually deploy.

QuotaGuard Static IP Blog

Practical notes on routing cloud and AI traffic through Static IPs.

Reliability Engineered for the Modern Cloud

For over a decade, QuotaGuard has provided reliable, high-performance static IP and proxy solutions for cloud environments like Heroku, Kubernetes, and AWS.

Get the fixed identity and security your application needs today.