# Static IP for Cloud Run and Cloud Functions

Source: https://prontaro.com/docs/integrations/google-cloud-run/

Route allowlisted calls from Cloud Run and Cloud Functions through a fixed IPv4 without managing VPC subnets or paying for Cloud NAT.

Cloud Run services, Cloud Run Jobs, and Cloud Functions (2nd gen) exit from shared rotating Google Cloud ranges by default. Google’s native static IP stack requires a VPC, Serverless VPC Access (or Direct VPC Egress), Cloud Router, and Cloud NAT, adding 24/7 hourly fees and per-GB charges. With Prontaro, regular service traffic stays direct while selected calls route through your `/32` — configured with a single environment variable.

## Prontaro and Cloud NAT with Serverless VPC Access

| Dimension | Prontaro | Cloud NAT + Serverless VPC Access |
| --- | --- | --- |
| **Setup** | 5 minutes: one environment variable or secret | VPC, subnets, connector, Cloud Router, Cloud NAT, routing |
| **Traffic scope** | Only the external APIs you choose | All egress from the service (or custom subnet routing) |
| **Cost** | From $12/month (100 GB traffic included) | 24/7 hourly connector VMs + Cloud NAT hourly + per-GB fees |
| **IP reuse** | Same IP works in CI, local dev, and other clouds | Locked to one VPC in a single GCP region |

## Which method to choose

| Cloud Run / Cloud Functions task | Prontaro method | Best for |
| --- | --- | --- |
| **Partner HTTPS APIs and payment gateways** | HTTPS proxy (`PRONTARO_PROXY_URL`) | End-to-end TLS and mTLS over HTTP CONNECT (`:443`) |
| **Single REST API without proxy libraries** | [Relay URL](https://prontaro.com/docs/outbound/relay.md) (`PRONTARO_RELAY_URL`) | Swap only the base URL in built-in `fetch` |
| **Allowlisted external databases** | `socks5h://` or `prontaro forward` | Forwards TCP connections to PostgreSQL and MongoDB |

## Prerequisites

- A Prontaro account on Dedicated (from $12/month) or Pro ([plans and pricing](https://prontaro.com/docs/billing/plans.md)).
- A dedicated IPv4 in the Prontaro location closest to your GCP region (available locations are shown in the dashboard).
- A Google Cloud project with `gcloud` CLI installed (or Google Cloud Console access).

## Step 1. Create proxy credentials and allowlist your IP

Add your dedicated IPv4 (`/32`) to the partner allowlist, then create dedicated proxy credentials for Cloud Run in the dashboard. Leave the **To** destination list open until you verify the outbound IP.

1. Open **IP addresses** in [my.prontaro.com](https://my.prontaro.com/ips) and click **Create proxy credentials**.
2. Name them `cloud-run-prod` and copy the `HTTPS` URL (port `:443`).

IP addresses Proxy credentials [Open in dashboard](https://my.prontaro.com/ips)

## Step 2. Pass `PRONTARO_PROXY_URL` to Cloud Run or Cloud Functions

### Production: Google Secret Manager (recommended)

Store the URL in Secret Manager, grant your Cloud Run service account `roles/secretmanager.secretAccessor`, and expose it as `PRONTARO_PROXY_URL`:

```bash
printf '%s' "https://u_gcp:s3cr3t@<entry>.prontaro.io:443" \
  | gcloud secrets create prontaro-proxy-url --data-file=-

# For Cloud Run:
gcloud run services update my-service \
  --region europe-west3 \
  --set-secrets="PRONTARO_PROXY_URL=prontaro-proxy-url:latest"

# For Cloud Functions (2nd gen):
gcloud functions deploy my-function \
  --gen2 \
  --region europe-west3 \
  --set-secrets="PRONTARO_PROXY_URL=prontaro-proxy-url:latest"
```

### Quick start with `--set-env-vars`

For fast testing, set the environment variable directly on a new revision:

```bash
gcloud run services update my-service \
  --region europe-west3 \
  --set-env-vars="PRONTARO_PROXY_URL=https://u_gcp:s3cr3t@<entry>.prontaro.io:443"
```

Or configure it in the Google Cloud Console:

**Cloud Run → Service → Edit & deploy new revision → Variables & Secrets**

- `PRONTARO_PROXY_URL`: `https://u_gcp:s3cr3t@<entry>.prontaro.io:443`

> **Do not set a global HTTPS_PROXY on Cloud Run**
>
> Google Cloud SDKs (Cloud Storage, Firestore, Pub/Sub, Secret Manager) and calls to the GCP metadata server (`169.254.169.254`, `metadata.google.internal`) honor a global `HTTPS_PROXY`.
>
> Pass `PRONTARO_PROXY_URL` explicitly only to the client calling allowlisted external APIs so internal GCP traffic stays fast and never burns your Prontaro traffic quota.

## Step 3. Configure the HTTP client in code

### Node.js 20+ (`undici`)

Install `undici` (`npm install undici`) and instantiate `ProxyAgent` once at module scope so concurrent Cloud Run requests reuse connections:

```js
// src/partner.mjs
import { fetch, ProxyAgent } from 'undici';

const proxyUrl = process.env.PRONTARO_PROXY_URL;
if (!proxyUrl) {
  throw new Error('PRONTARO_PROXY_URL is not configured');
}

const agent = new ProxyAgent({
  uri: proxyUrl,
  connections: 20,
});

export async function callPartner(path = '/v1/status') {
  const response = await fetch(`https://api.example.com${path}`, {
    dispatcher: agent,
    headers: {
      Authorization: `Bearer ${process.env.PARTNER_API_TOKEN}`,
    },
    signal: AbortSignal.timeout(15_000),
  });
  if (!response.ok) {
    throw new Error(`Partner API returned ${response.status}`);
  }
  return response.json();
}
```

### Python 3.11+ (`httpx`)

Install `httpx` (`pip install httpx`) and keep a single module-level client:

```python
# partner.py
import os
import httpx

client = httpx.Client(
    proxy=os.environ["PRONTARO_PROXY_URL"],
    timeout=httpx.Timeout(15.0, connect=5.0),
    limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
)

def call_partner(path: str = "/v1/status") -> dict:
    response = client.get(
        f"https://api.example.com{path}",
        headers={"Authorization": f"Bearer {os.environ['PARTNER_API_TOKEN']}"},
    )
    response.raise_for_status()
    return response.json()
```

The exact same code works in Cloud Run Jobs and Cloud Functions (2nd gen).

## Step 4. Verify the outbound IP

Before restricting allowed destinations, point a temporary check endpoint at `https://api.ipify.org?format=json`, deploy the revision, and call it:

```
 
{"ip":"203.0.113.10"}
```

Confirm the returned address matches your dedicated IPv4 in [my.prontaro.com](https://my.prontaro.com/), then remove the check route.

## Step 5. Lock down allowed destinations

Once verified, restrict `cloud-run-prod` to the exact partner hosts and ports:

1. Open **IP addresses → Proxy credentials** in [my.prontaro.com](https://my.prontaro.com/ips), select `cloud-run-prod`, switch to **Access**, and add `api.example.com:443` under **To**.
2. Save.

IP addresses Proxy credentials Access [Open in dashboard](https://my.prontaro.com/ips)

## Google Cloud Run notes and limits

- **Pair close regions:** pick the Prontaro location in the dashboard closest to your Cloud Run region to minimize latency.
- **Autoscaling and connection pools:** each instance opens its own pool, while [connection limits](https://prontaro.com/docs/billing/limits.md) apply per IP. Keep `connections` / `max_connections` at `10–20` and set `--max-instances`.
- **Cloud Run Jobs:** work identically; for batch jobs reaching allowlisted databases, use `socks5h://` or `prontaro forward` with `PRONTARO_KEY` exposed from Secret Manager.
- **[BGP failover](https://prontaro.com/docs/outbound/failover.md):** on a server outage or reboot, Prontaro moves your `/32` to a standby Prontaro server without changing the allowlisted IP. Active TCP sessions close; retries immediately resume from the same IP.

## Common errors

| Symptom | Cause | Fix |
| --- | --- | --- |
| `PERMISSION_DENIED` on deploy with `--set-secrets` | Cloud Run service account cannot read the Secret Manager secret. | Grant `roles/secretmanager.secretAccessor` on `prontaro-proxy-url`. |
| `407 Proxy Authentication Required` | Trailing newline in the Secret Manager payload, or new credentials are still propagating. | Write the secret without a newline (`printf '%s'`) and copy the exact URL under [IP addresses](https://my.prontaro.com/ips). |
| `403 Forbidden` from proxy | Target host or port is missing from the **To** list. | Add `<host>:443` under **To** in the credentials’ **Access** tab. |
| GCP metadata errors or unexpected Prontaro traffic | Global `HTTPS_PROXY` intercepted `googleapis.com` or `169.254.169.254`. | Remove global `HTTPS_PROXY` and pass `PRONTARO_PROXY_URL` only to external API clients. |

## Next steps

- [Static IP for AWS Lambda](https://prontaro.com/docs/integrations/aws-lambda.md) — the same pattern for AWS Lambda without VPC or NAT Gateway.
- [PostgreSQL and AWS RDS with a static IP](https://prontaro.com/docs/integrations/postgres.md) — TLS and driver setup for allowlisted databases.
- [Language guides](https://prontaro.com/docs/languages/) — proxy examples for Node.js, Python, Go, PHP, and Java.
- [HTTP & SOCKS5 proxy](https://prontaro.com/docs/outbound/proxy.md) — proxy credentials, protocols, and allowed destination rules.
