عرض المحتوى الديناميكي واستضافة الخدمات المصغَّرة باستخدام Cloud Run

يمكنك إقران Cloud Run مع Firebase Hosting لإنشاء المحتوى الديناميكي وعرضه أو إنشاء واجهات برمجة تطبيقات REST كخدمات مصغّرة.

باستخدام Cloud Run، يمكنك نشر تطبيق مُجمَّع في صورة حاوية. بعد ذلك، باستخدام Firebase Hosting، يمكنك توجيه طلبات HTTPS لتشغيل تطبيقك المُدار في حاويات.

  • تتيح منصة Cloud Run استخدام لغات متعددة (بما في ذلك Go وNode.js وPython وJava)، ما يمنحك المرونة لاستخدام لغة البرمجة وإطار العمل الذي تختاره.
  • Cloud Run توسّع تلقائيًا وأفقيًا صورة الحاوية للتعامل مع الطلبات المستلَمة، ثم تقلّصها عند انخفاض الطلب.
  • تدفع فقط مقابل وحدة المعالجة المركزية والذاكرة والشبكة المستهلكة أثناء معالجة الطلب.

للاطّلاع على أمثلة على حالات الاستخدام ونماذج لـ Cloud Run المدمج مع Firebase Hosting، يُرجى الانتقال إلى نظرة عامة على الحوسبة بدون خادم.


يوضّح لك هذا الدليل كيفية تنفيذ ما يلي:

  1. كتابة تطبيق Hello World بسيط
  2. وضع تطبيق في حاوية وتحميله إلى Artifact Registry
  3. نشر صورة الحاوية في Cloud Run
  4. توجيه طلبات Hosting إلى تطبيقك المُدار في حاويات

لتحسين أداء عرض المحتوى الديناميكي، يمكنك اختياريًا ضبط إعدادات ذاكرة التخزين المؤقت.

قبل البدء

قبل استخدام Cloud Run، عليك إكمال بعض المهام الأولية، بما في ذلك إعداد حساب Cloud Billing وتفعيل واجهة برمجة تطبيقات Cloud Run وتثبيت أداة سطر الأوامر gcloud.

إعداد الفوترة لمشروعك

يوفّر Cloud Run حصّة استخدام مجانية، ولكن يجب أن يكون لديك حساب على Cloud Billing مرتبط بمشروع Firebase لاستخدام Cloud Run أو تجربته.

تفعيل واجهة برمجة التطبيقات وتثبيت حزمة تطوير البرامج (SDK)

  1. فعِّل واجهة برمجة تطبيقات Cloud Run في وحدة تحكّم Google APIs:

    1. افتح صفحة واجهة برمجة تطبيقات Cloud Run في وحدة تحكّم Google APIs.

    2. اختَر مشروع Firebase عندما يُطلب منك ذلك.

    3. انقر على تفعيل في صفحة واجهة برمجة التطبيقات Cloud Run.

  2. ثبِّت حزمة Cloud SDK وابدأها.

  3. تأكَّد من ضبط أداة gcloud للمشروع الصحيح:

    gcloud config list

الخطوة 1: كتابة نموذج التطبيق

يُرجى العِلم أنّ Cloud Run يتيح استخدام العديد من اللغات الأخرى بالإضافة إلى اللغات المعروضة في النموذج التالي.

متابعة

  1. أنشئ دليلاً جديدًا باسم helloworld-go، ثم غيِّر الدليل إليه:

    mkdir helloworld-go
    cd helloworld-go
    1. أنشئ ملفًا جديدًا باسم helloworld.go، ثم أضِف الرمز التالي:
    package main
    
    import (
    	"fmt"
    	"log"
    	"net/http"
    	"os"
    )
    
    func handler(w http.ResponseWriter, r *http.Request) {
    	log.Print("helloworld: received a request")
    	target := os.Getenv("TARGET")
    	if target == "" {
    		target = "World"
    	}
    	fmt.Fprintf(w, "Hello %s!\n", target)
    }
    
    func main() {
    	log.Print("helloworld: starting server...")
    
    	http.HandleFunc("/", handler)
    
    	port := os.Getenv("PORT")
    	if port == "" {
    		port = "8080"
    	}
    
    	log.Printf("helloworld: listening on port %s", port)
    	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
    }
    

    تنشئ هذه التعليمة البرمجية خادم ويب أساسيًا يستمع إلى المنفذ المحدّد بواسطة متغيّر البيئة PORT.

اكتمل تطبيقك وأصبح جاهزًا لوضعه في حاوية وتحميله إلى Artifact Registry.

Node.js

  1. أنشئ دليلاً جديدًا باسم helloworld-nodejs، ثم غيِّر الدليل إليه:

    mkdir helloworld-nodejs
    cd helloworld-nodejs
  2. أنشِئ ملف package.json بالمحتوى التالي:

    {
      "name": "knative-serving-helloworld",
      "version": "1.0.0",
      "description": "Simple hello world sample in Node",
      "main": "index.js",
      "scripts": {
        "start": "node index.js",
        "check": "node --check index.js"
      },
      "engines": {
        "node": ">=24"
      },
      "author": "",
      "license": "Apache-2.0",
      "dependencies": {
        "express": "^5.3.0"
      }
    }
    
  3. أنشئ ملفًا جديدًا باسم index.js، ثم أضِف الرمز التالي:

    const express = require('express');
    const app = express();
    
    app.get('/', (req, res) => {
      console.log('Hello world received a request.');
    
      const target = process.env.TARGET || 'World';
      res.send(`Hello ${target}!\n`);
    });
    
    const port = process.env.PORT || 8080;
    app.listen(port, () => {
      console.log('Hello world listening on port', port);
    });
    

    تنشئ هذه التعليمة البرمجية خادم ويب أساسيًا يستمع إلى المنفذ المحدّد بواسطة متغيّر البيئة PORT.

اكتمل تطبيقك وأصبح جاهزًا لوضعه في حاوية وتحميله إلى Artifact Registry.

Python

  1. أنشئ دليلاً جديدًا باسم helloworld-python، ثم غيِّر الدليل إليه:

    mkdir helloworld-python
    cd helloworld-python
  2. أنشئ ملفًا جديدًا باسم app.py، ثم أضِف الرمز التالي:

    import os
    
    from flask import Flask
    
    app = Flask(__name__)
    
    
    @app.route("/")
    def hello_world():
        target = os.environ.get("TARGET", "World")
        return f"Hello {target}!\n"
    
    
    if __name__ == "__main__":
        app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "8080")))
    

    تنشئ هذه التعليمة البرمجية خادم ويب أساسيًا يستمع إلى المنفذ المحدّد بواسطة متغيّر البيئة PORT.

اكتمل تطبيقك وأصبح جاهزًا لوضعه في حاوية وتحميله إلى Artifact Registry.

Java

  1. ثبِّت Java SE 8 أو إصدار أحدث من JDK وCURL.

    يُرجى العِلم أنّنا نحتاج إلى إجراء ذلك فقط لإنشاء مشروع الويب الجديد في الخطوة التالية. سيحمّل ملف Dockerfile، الموضَّح لاحقًا، جميع التبعيات في الحاوية.

  2. من وحدة التحكّم، أنشِئ مشروع ويب فارغًا جديدًا باستخدام cURL، ثم أوامر فك الضغط:

    curl https://start.spring.io/starter.zip \
        -d dependencies=web \
        -d name=helloworld \
        -d artifactId=helloworld \
        -o helloworld.zip
    unzip helloworld.zip

    يؤدي ذلك إلى إنشاء مشروع SpringBoot.

  3. عدِّل فئة SpringBootApplication في src/main/java/com/example/helloworld/HelloworldApplication.java من خلال إضافة @RestController لمعالجة عملية ربط / وأضِف أيضًا حقل @Value لتوفير متغيّر بيئة TARGET:

    package com.example.helloworld;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @SpringBootApplication
    public class HelloworldApplication {
    
      @Value("${TARGET:World}")
      String target;
    
      @RestController
      class HelloworldController {
        @GetMapping("/")
        String hello() {
          return "Hello " + target + "!";
        }
      }
    
      public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class, args);
      }
    }
    

    تنشئ هذه التعليمة البرمجية خادم ويب أساسيًا يستمع إلى المنفذ المحدّد بواسطة متغيّر البيئة PORT.

اكتمل تطبيقك وأصبح جاهزًا لوضعه في حاوية وتحميله إلى Artifact Registry.

الخطوة 2: وضع تطبيق في حاوية وتحميله إلى Artifact Registry

  1. يمكنك وضع نموذج التطبيق في حاوية من خلال إنشاء ملف جديد باسم Dockerfile في الدليل نفسه الذي يتضمّن الملفات المصدر. انسخ المحتوى التالي في ملفك.

    متابعة

    # Use the official Golang image to create a build artifact.
    # Use the supported Go 1.27 release track.
    FROM golang:1.27 AS builder
    
    ARG TARGETOS
    ARG TARGETARCH
    
    # Create and change to the app directory.
    WORKDIR /app
    
    # Copy local code to the container image.
    COPY . ./
    
    # Install dependencies and tidy up the go.mod and go.sum files.
    RUN go mod tidy
    
    # Build the binary.
    # -mod=readonly ensures immutable go.mod and go.sum in container builds.
    RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -mod=readonly -v -o server
    
    # Use the official Alpine image for a lean production container.
    # https://hub.docker.com/_/alpine
    # https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
    FROM alpine:3.24
    RUN apk add --no-cache ca-certificates
    
    # Copy the binary to the production image from the builder stage.
    COPY --from=builder /app/server /server
    
    # Run the web service on container startup.
    CMD ["/server"]
    

    Node.js

    # Use the official lightweight Node.js 24 LTS image.
    # https://hub.docker.com/_/node
    FROM node:25-bookworm-slim
    
    # Create and change to the app directory.
    WORKDIR /usr/src/app
    
    # Copy application dependency manifests to the container image.
    # A wildcard is used to ensure both package.json AND package-lock.json are copied.
    # Copying this separately prevents re-running npm ci on every code change.
    COPY package*.json ./
    
    # Install production dependencies.
    RUN npm ci --omit=dev
    
    # Copy local code to the container image.
    COPY . ./
    
    # Run the web service on container startup.
    CMD [ "node", "index.js" ]
    

    Python

    # Use the official lightweight Python image.
    # https://hub.docker.com/_/python
    FROM python:3.15.0-slim-trixie
    
    # Allow statements and log messages to immediately appear in the Knative logs
    ENV PYTHONUNBUFFERED=1
    
    # Knative supplies PORT; default to 8080 for local runs.
    ENV PORT=8080
    WORKDIR /app
    
    # Install pinned production dependencies before copying application code.
    COPY requirements.txt ./
    RUN python -m pip install --no-cache-dir -r requirements.txt
    
    COPY app.py ./
    
    # Run the web service on container startup. Here we use the gunicorn
    # webserver, with one worker process and 8 threads.
    # For environments with multiple CPU cores, increase the number of workers
    # to be equal to the cores available.
    CMD ["sh", "-c", "exec gunicorn --bind \"0.0.0.0:${PORT:-8080}\" --workers 1 --threads 8 --timeout 0 app:app"]
    

    Java

    # Use the official Maven/Java 25 LTS image to build: https://hub.docker.com/_/maven
    FROM maven:3.9-eclipse-temurin-26 AS builder
    
    # Copy local code to the container image.
    WORKDIR /app
    COPY pom.xml .
    COPY src ./src
    
    # Build the executable jar.
    RUN mvn --batch-mode --no-transfer-progress package
    
    # Use the Eclipse Temurin Java 25 LTS runtime for the production stage.
    # https://hub.docker.com/_/eclipse-temurin
    # https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
    FROM eclipse-temurin:25-jre-noble
    
    # Copy the jar to the production image from the builder stage.
    COPY --from=builder /app/target/helloworld-*.jar /helloworld.jar
    
    # Run the web service on container startup.
    CMD ["java", "-jar", "/helloworld.jar"]
    

  2. أنشئ صورة الحاوية باستخدام Cloud Build من خلال تشغيل الأمر التالي من الدليل الذي يحتوي على ملف Dockerfile:

    gcloud builds submit --tag gcr.io/PROJECT_ID/helloworld

    في حال نجاح العملية، ستظهر رسالة SUCCESS (نجاح) تحتوي على اسم الصورة
    (gcr.io/PROJECT_ID/helloworld).

يتم الآن تخزين صورة الحاوية في Artifact Registry ويمكن إعادة استخدامها إذا أردت ذلك.

يُرجى العِلم أنّه بدلاً من Cloud Build، يمكنك استخدام إصدار مثبَّت محليًا من Docker لإنشاء الحاوية محليًا.

الخطوة 3: نشر صورة الحاوية في Cloud Run

  1. انشرها باستخدام الأمر التالي:

    gcloud run deploy --image gcr.io/PROJECT_ID/helloworld

  2. عندما يُطلب منك ذلك:

  3. انتظِر بضع لحظات حتى يكتمل النشر. في حال نجاح العملية، يعرض سطر الأوامر عنوان URL للخدمة. على سبيل المثال: https://helloworld-RANDOM_HASH-us-central1.a.run.app

  4. انتقِل إلى الحاوية المنشورة من خلال فتح عنوان URL للخدمة في متصفّح ويب.

توضّح لك الخطوة التالية كيفية الوصول إلى هذا التطبيق المُدار في حاويات من عنوان URL لخدمة Firebase Hosting لكي يتمكّن من إنشاء محتوى ديناميكي لموقعك الإلكتروني المستضاف على Firebase.

الخطوة 4: توجيه طلبات الاستضافة إلى تطبيقك المستند إلى حاويات

باستخدام قواعد إعادة الكتابة، يمكنك توجيه الطلبات التي تتطابق مع أنماط معيّنة إلى وجهة واحدة.

يوضّح المثال التالي كيفية توجيه جميع الطلبات من الصفحة /helloworld على موقعك الإلكتروني Hosting لتشغيل مثيل حاوية helloworld.

  1. تأكَّد ممّا يلي:

    للحصول على تعليمات تفصيلية حول تثبيت واجهة سطر الأوامر وإعداد Hosting، يُرجى الاطّلاع على دليل البدء في استخدام Hosting.

  2. افتح ملف firebase.json.

  3. أضِف إعدادات rewrite التالية ضمن قسم hosting:

    "hosting": {
      // ...
    
      // Add the "rewrites" attribute within "hosting"
      "rewrites": [ {
        "source": "/helloworld",
        "run": {
          "serviceId": "helloworld",  // "service name" (from when you deployed the container image)
          "region": "us-central1",    // optional (if omitted, default is us-central1)
          "pinTag": true              // optional (see note below)
        }
      } ]
    }
  4. انشر إعدادات الاستضافة على موقعك الإلكتروني من خلال تنفيذ الأمر التالي من جذر دليل مشروعك:

    firebase deploy --only hosting

يمكن الآن الوصول إلى الحاوية من خلال عناوين URL التالية:

  • نطاقاتك الفرعية في Firebase:
    PROJECT_ID.web.app/ و PROJECT_ID.firebaseapp.com/

  • أي نطاقات خاصة مرتبطة:
    CUSTOM_DOMAIN/

انتقِل إلى صفحة إعدادات Hosting للحصول على مزيد من التفاصيل حول قواعد إعادة الكتابة. يمكنك أيضًا التعرّف على ترتيب أولوية الردود لإعدادات Hosting المختلفة.

الاختبار محليًا

أثناء عملية التطوير، يمكنك تشغيل صورة الحاوية واختبارها محليًا. للحصول على تعليمات مفصّلة، يُرجى الاطّلاع على مستندات Cloud Run.

الخطوات التالية