קישור Firebase App Hosting לרשת VPC
קל לארגן דפים בעזרת אוספים
אפשר לשמור ולסווג תוכן על סמך ההעדפות שלך.
הקצה העורפי Firebase App Hosting יכול להתחבר לרשת ענן וירטואלי פרטי (VPC). כך אפשר לאפליקציית הקצה העורפי Firebase App Hosting לגשת לשירותי קצה עורפי שלא נגישים באמצעות כתובות IP ציבוריות, כמו Cloud SQL, Spanner, Cloud Memorystore, Compute Engine או מיקרו-שירותים פנימיים של Kubernetes.
הגישה ל-VPC זמינה רק בזמן הריצה (מתוך מאגר Cloud Run), ולא בזמן הבנייה (Cloud Build).
בחירה של דרך להתחבר לרשת VPC
- יציאה ישירה מ-VPC: פשוטה יותר, מהירה יותר וזולה יותר. משתמשים בכתובת IP אחת לכל מאגר.
מומלץ לרוב תרחישי השימוש.
- מחברים ללא שרתים: מאגדים כתובות IP לאפליקציות גדולות יותר. נדרש תשלום על מכונת ה-VM הבסיסית. פרטים על התמחור מופיעים בקטע 'חיבור לרשת (VPC) מאפליקציית serverless' בדף התמחור של VPC.
כדי להגדיר גישה, משתמשים במיפוי vpcAccess
בקובץ apphosting.yaml
.
משתמשים בשם מלא של הרשת או המחבר, או במזהה. שימוש במזהים מאפשר ניידות בין סביבות ביניים וסביבות ייצור עם מחברים או רשתות שונים.
הגדרת תעבורת נתונים יוצאת (egress) ישירה מ-VPC (apphosting.yaml
):
runConfig:
vpcAccess:
egress: PRIVATE_RANGES_ONLY # Default value
networkInterfaces:
# Specify at least one of network and/or subnetwork
- network: my-network-id
subnetwork: my-subnetwork-id
הגדרת מחבר ללא שרת (apphosting.yaml
):
runConfig:
vpcAccess:
egress: ALL_TRAFFIC
connector: connector-id
דוגמה: התחברות ל-Memorystore for Redis מאפליקציית Next.js
מערכות שמירה במטמון כמו Redis או Memcached משמשות בדרך כלל ליצירת שכבת שמירה במטמון נתונים מהירה לאפליקציה. בדוגמה הזו מוסבר איך להגדיר את Memorystore for Redis באותו פרויקט Google Cloud כמו קצה העורפי (backend) של Firebase App Hosting, ואיך להתחבר אליו באמצעות יציאה ישירה מ-VPC.
שלב 0: יצירת מכונה של Memorystore for Redis
- נכנסים לדף Memorystore for Redis במסוף Google Cloud.
- מוודאים שבחרתם באותו פרויקט שבו אתם משתמשים ב-Firebase App Hosting.
- אם אין לכם גישה לדף הזה, צריך לוודא שהחיוב מופעל בפרויקט ושהפעלתם את Memorystore API.
- בוחרים באפשרות Create Instance (יצירת מופע).
- מגדירים את המופע החדש עם ההגדרות המועדפות. הנה כמה דוגמאות לערכים שאפשר להשתמש בהם:
- מזינים
my-redis-cache
בשדה Instance ID (מזהה מכונה).
- מזינים
Redis cache
בשדה שם לתצוגה.
- בבורר הרמות, בוחרים באפשרות Basic. בדרגת Basic מוגדר צומת Redis עצמאי, בניגוד לדרגת Standard שבה נעשה שימוש בצומת משוכפל לגיבוי הנתונים.
- בוחרים את האזור של ה-backend של App Hosting מבורר Region (אזור).
חשוב להגדיר את הערך הזה כך שיתאים לאזור של ה-Backend.
- בוחרים באפשרות כל בבורר האזורים.
- מזינים
5
בקטע קיבולת. הפעולה הזו מגדירה את קיבולת המופע ל-5GB.
- בוחרים באפשרות
5.0
בקטע גרסה (מומלץ).
- בוחרים באפשרות ברירת מחדל מתוך בורר הרשת המורשית.
שלב 1: מעדכנים את apphosting.yaml
עם מזהה רשת ה-VPC
- נכנסים לדף רשתות ה-VPC במסוף Google Cloud.
- מחפשים את מזהה רשת ה-VPC של מכונת Memorystore for Redis (לרוב זה יהיה
default
).
מגדירים יציאה ישירה מ-VPC ב-apphosting.yaml
באמצעות מזהה רשת ה-VPC:
runConfig:
vpcAccess:
egress: PRIVATE_RANGES_ONLY # Default value
networkInterfaces:
- network: my-network-id
שלב 2: מוסיפים משתני סביבה שמפנים את האפליקציה אל Redis
- אפשר למצוא את פרטי החיבור (המארח והיציאה) בכרטיסייה 'חיבורים' של מופע Memorystore for Redis במסוף Google Cloud.
מתחברים ל-Redis באמצעות משתני הסביבה REDISPORT
ו-REDISHOST
. מגדירים את הערכים האלה ב-apphosting.yaml
באמצעות ערכי המארח והיציאה ממסוף Google Cloud:
env:
# Sample only. Use actual values provided by Memorystore
- variable: REDISPORT
value: 6379
- variable: REDISHOST
value: 10.127.16.3
שלב 3: שימוש ב-Redis מהאפליקציה
מתקינים את חבילת npm redis:
npm install redis@latest
ניגשים למטמון redis מהקוד. משתמשים במשתני הסביבה שהוגדרו בשלב הקודם. לדוגמה, כך אפשר לקרוא ממאגר מטמון ב-Next.js handler של נתיב:
src/lib/redis.js
import { createClient } from "redis";
// Set these environment variables in apphosting.yaml
const REDISHOST = process.env.REDISHOST;
const REDISPORT = process.env.REDISPORT;
let redisClient;
export async function getClient(req, res) {
// Only connect if a connection isn't already available
if (!redisClient) {
redisClient = await createClient(REDISPORT, REDISHOST)
.on("error", (err) => console.error("Redis Client Error", err))
.connect();
}
return redisClient;
}
src/app/counter/route.js
import { getClient } from "@/lib/redis.js";
export async function GET(request) {
const redisClient = await getClient();
const count = await redisClient.get("counter");
return Response.json({ count });
}
export async function POST(request) {
const redisClient = await getClient();
const count = await redisClient.incr("counter");
return Response.json({ count });
}
שלב 4 (אופציונלי): הגדרת האפליקציה לפיתוח מקומי
אפשר להשתמש ב-Firebase App Hosting כדי לשנות ערכים באמצעות apphosting.emulator.yaml
. כאן אפשר לשנות את הערך של REDISHOST
כך שיצביע על המארח המקומי, כדי שתוכלו לפתח באופן מקומי באמצעות התקנה מקומית של Redis.
- התקנת Redis במחשב המקומי
יוצרים או עורכים apphosting.emulators.yaml
כדי להפנות למופע המקומי:
env:
- variable: REDISHOST
value: 127.0.0.1
אלא אם צוין אחרת, התוכן של דף זה הוא ברישיון Creative Commons Attribution 4.0 ודוגמאות הקוד הן ברישיון Apache 2.0. לפרטים, ניתן לעיין במדיניות האתר Google Developers. Java הוא סימן מסחרי רשום של חברת Oracle ו/או של השותפים העצמאיים שלה.
עדכון אחרון: 2025-08-08 (שעון UTC).
[null,null,["עדכון אחרון: 2025-08-08 (שעון UTC)."],[],[],null,["\u003cbr /\u003e\n\nYour Firebase App Hosting backend can connect to a [Virtual Private Cloud\n(VPC)](https://cloud.google.com/vpc/docs) network. This allows your\nFirebase App Hosting backend to access backend services not accessible using\npublic IP addresses, such as Cloud SQL, Spanner, Cloud Memorystore,\nCompute Engine, or Kubernetes internal microservices.\n\nVPC access is only available at runtime (from your Cloud Run\ncontainer), not at build time (Cloud Build).\n\nChoose how to connect to a VPC network\n\n- [Direct VPC\n Egress](https://cloud.google.com/run/docs/configuring/vpc-direct-vpc): Simpler, faster, and less expensive. Uses one IP address per container. Recommended for most use cases.\n- [Serverless\n Connectors](https://cloud.google.com/vpc/docs/serverless-vpc-access): Pools IP addresses for larger applications. Requires payment for the underlying VM. See \"Serverless VPC Access\" in the [VPC pricing page](https://cloud.google.com/vpc/network-pricing) for pricing details.\n\nConfigure in `apphosting.yaml`\n\nUse the `vpcAccess` mapping in your `apphosting.yaml` file to configure access.\nUse either a fully qualified network/connector name or an ID. Using IDs allows\nfor portability between staging and production environments with different\nconnectors/networks.\n\nDirect VPC Egress Configuration (`apphosting.yaml`): \n\n runConfig:\n vpcAccess:\n egress: PRIVATE_RANGES_ONLY # Default value\n networkInterfaces:\n # Specify at least one of network and/or subnetwork\n - network: my-network-id\n subnetwork: my-subnetwork-id\n\nServerless Connector Configuration (`apphosting.yaml`): \n\n runConfig:\n vpcAccess:\n egress: ALL_TRAFFIC\n connector: connector-id\n\nExample: connect to Memorystore for Redis from a Next.js app\n\nCaching systems like Redis or Memcached are commonly used to build a fast data\ncaching layer for an app. This example shows you how to set up\n[Memorystore for Redis](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview)\nin the same Google Cloud project as your Firebase App Hosting backend and\nconnect to it using\n[Direct VPC egress](https://cloud.google.com/run/docs/configuring/vpc-direct-vpc).\n\nStep 0: Create a Memorystore for Redis instance **Note:** you may also be prompted to create a [service connection policy](https://cloud.google.com/vpc/docs/about-service-connection-policies) as part of this setup.\n\n1. Go to the [*Memorystore for Redis* page](https://console.cloud.google.com/memorystore/redis/instances) in the Google Cloud console.\n - Make sure the same project you're using for Firebase App Hosting is selected.\n - If you can't access this page, make sure billing is enabled for your project and that you've enabled the [Memorystore API](https://console.cloud.google.com/apis/dashboard).\n2. Select **Create Instance**.\n3. Configure the new instance with your preferred settings. Here are some example values you can use:\n - Enter `my-redis-cache` under **Instance ID**.\n - Enter `Redis cache` under **Display name**.\n - Choose **Basic** under the tier selector. Basic tier designates a standalone Redis node, as opposed to standard tier, which uses a replica node to backup your data.\n - Choose your App Hosting backend's region from the **Region** selector. **Be sure to set this value to match the region of your backend.**\n - Choose **any** from the zone selector.\n - Enter `5` under **Capacity**. This sets your instance capacity to 5 GB.\n - Select `5.0` under **Version** (recommended).\n - Choose **default** from the **Authorized network** selector.\n\nStep 1: Update `apphosting.yaml` with your VPC network ID\n\n1. Visit the [VPC networks page](/docs/app-hosting/console.cloud.google.com/networking/networks/list) in the Google Cloud console.\n2. Find the VPC network ID for your Memorystore for Redis instance (it will often be `default`).\n3. Set direct VPC egress configuration in `apphosting.yaml` using the VPC\n network ID:\n\n runConfig:\n vpcAccess:\n egress: PRIVATE_RANGES_ONLY # Default value\n networkInterfaces:\n - network: my-network-id\n\nStep 2: Add environment variables that direct your app to Redis\n\n1. Find connection information (host and port) in the \"Connections\" tab of your Memorystore for Redis instance in the Google Cloud console.\n2. Connect to Redis with `REDISPORT` and `REDISHOST` environment variables. Set\n these in `apphosting.yaml` using the host and port values from the\n Google Cloud console:\n\n env:\n # Sample only. Use actual values provided by Memorystore\n - variable: REDISPORT\n value: 6379\n - variable: REDISHOST\n value: 10.127.16.3\n\nStep 3: Use redis from your app\n\n1. Install the [redis](https://www.npmjs.com/package/redis) npm package:\n\n `npm install redis@latest`\n2. Access your redis cache from your code. Use the environment variables\n configured in the previous step. For example, here's how you might read from\n a cache in a Next.js route handler:\n\n - `src/lib/redis.js`\n\n import { createClient } from \"redis\";\n\n // Set these environment variables in apphosting.yaml\n const REDISHOST = process.env.REDISHOST;\n const REDISPORT = process.env.REDISPORT;\n\n let redisClient;\n\n export async function getClient(req, res) {\n // Only connect if a connection isn't already available\n if (!redisClient) {\n redisClient = await createClient(REDISPORT, REDISHOST)\n .on(\"error\", (err) =\u003e console.error(\"Redis Client Error\", err))\n .connect();\n }\n\n return redisClient;\n }\n\n - `src/app/counter/route.js`\n\n import { getClient } from \"@/lib/redis.js\";\n\n export async function GET(request) {\n const redisClient = await getClient();\n const count = await redisClient.get(\"counter\");\n\n return Response.json({ count });\n }\n\n export async function POST(request) {\n const redisClient = await getClient();\n const count = await redisClient.incr(\"counter\");\n\n return Response.json({ count });\n }\n\nStep 4 (optional): Configure your app for local development\n\nThe Firebase App Hosting emulator can override values using\n`apphosting.emulator.yaml`. Here, you can change the value of `REDISHOST` to\npoint to the localhost so that you can develop locally using a local\ninstallation of Redis.\n\n1. [Install Redis on your local machine](https://redis.io/docs/latest/operate/oss_and_stack/install/install-redis/)\n2. Create or edit `apphosting.emulators.yaml` to reference your local instance:\n\n env:\n - variable: REDISHOST\n value: 127.0.0.1"]]