שרת תוכן דינמי ומארח שירותי מיקרו עם Cloud Run

חבר את ה-Cloud Run עם Firebase Hosting כדי ליצור ולהגיש את התוכן הדינמי שלך או לבנות ממשקי API של REST כשירותי מיקרו.

באמצעות Cloud Run , אתה יכול לפרוס יישום ארוז בתמונת מכיל. לאחר מכן, באמצעות Firebase Hosting, תוכל להפנות בקשות HTTPS להפעלת האפליקציה המכולה שלך.

לדוגמה, שימוש במקרים ודוגמאות עבור Cloud Run המשולב עם Firebase Hosting, בקר בסקירה הכללית שלנו ללא שרת .


מדריך זה מראה לך כיצד:

  1. כתוב אפליקציה פשוטה של ​​Hello World
  2. הכנס אפליקציה למיכל והעלה אותה ל-Container Registry
  3. פרוס את תמונת המכולה ב-Cloud Run
  4. ישיר בקשות אירוח לאפליקציה המכולה שלך

שים לב שכדי לשפר את הביצועים של הגשת תוכן דינמי, אתה יכול לכוון את הגדרות המטמון שלך.

לפני שאתה מתחיל

לפני השימוש ב-Cloud Run, עליך להשלים כמה משימות ראשוניות, כולל הגדרת חשבון Cloud Billing, הפעלת ממשק ה-API של Cloud Run והתקנת כלי שורת הפקודה gcloud .

הגדר חיוב עבור הפרויקט שלך

Cloud Run מציע מכסת שימוש בחינם , אך עדיין חייב להיות לך חשבון Cloud Billing המשויך לפרויקט Firebase שלך ​​כדי להשתמש או לנסות את Cloud Run.

הפעל את ה-API והתקן את ה-SDK

  1. הפעל את Cloud Run API במסוף Google APIs:

    1. פתח את דף Cloud Run API במסוף Google APIs.

    2. כשתתבקש, בחר בפרויקט Firebase שלך.

    3. לחץ על הפעל בדף Cloud Run API.

  2. התקן ואתחל את Cloud SDK.

  3. בדוק שכלי gcloud מוגדר לפרויקט הנכון:

    gcloud config list

שלב 1 : כתוב את היישום לדוגמה

שימו לב ש-Cloud Run תומך בשפות רבות אחרות בנוסף לשפות המוצגות בדוגמה הבאה.

ללכת

  1. צור ספרייה חדשה בשם helloworld-go , ולאחר מכן שנה את הספרייה לתוכה:

    mkdir helloworld-go
    cd helloworld-go
  2. צור קובץ חדש בשם 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 .

האפליקציה שלך גמורה ומוכנה לאחסון במכולות ולהעלאה ל-Container 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"
      },
      "author": "",
      "license": "Apache-2.0",
      "dependencies": {
        "express": "^4.18.2"
      }
    }
    
  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 .

האפליקציה שלך גמורה ומוכנה לאחסון במכולות ולהעלאה ל-Container Registry.

פִּיתוֹן

  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 'Hello {}!\n'.format(target)
    
    if __name__ == "__main__":
        app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
    

    קוד זה יוצר שרת אינטרנט בסיסי שמאזין ליציאה המוגדרת על ידי משתנה הסביבה PORT .

האפליקציה שלך גמורה ומוכנה לאחסון במכולות ולהעלאה ל-Container 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 .

האפליקציה שלך גמורה ומוכנה לאחסון במכולות ולהעלאה ל-Container Registry.

שלב 2 : הכנס אפליקציה למיכל והעלה אותה ל-Container Registry

  1. הכנס את האפליקציה לדוגמה על ידי יצירת קובץ חדש בשם Dockerfile באותה ספרייה כמו קבצי המקור. העתק את התוכן הבא לקובץ שלך.

    ללכת

    # Use the official Golang image to create a build artifact.
    # This is based on Debian and sets the GOPATH to /go.
    FROM golang:latest as builder
    
    ARG TARGETOS
    ARG TARGETARCH
    
    # Create and change to the app directory.
    WORKDIR /app
    
    # Retrieve application dependencies using go modules.
    # Allows container builds to reuse downloaded dependencies.
    COPY go.* ./
    RUN go mod download
    
    # Copy local code to the container image.
    COPY . ./
    
    # 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
    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 12 image.
    # https://hub.docker.com/_/node
    FROM node:12-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 install on every code change.
    COPY package*.json ./
    
    # Install production dependencies.
    RUN npm install --only=production
    
    # Copy local code to the container image.
    COPY . ./
    
    # Run the web service on container startup.
    CMD [ "npm", "start" ]
    

    פִּיתוֹן

    # Use the official lightweight Python image.
    # https://hub.docker.com/_/python
    FROM python:3.7-slim
    
    # Allow statements and log messages to immediately appear in the Knative logs
    ENV PYTHONUNBUFFERED True
    
    # Copy local code to the container image.
    ENV APP_HOME /app
    WORKDIR $APP_HOME
    COPY . ./
    
    # Install production dependencies.
    RUN pip install Flask gunicorn
    
    # 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 exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 app:app
    

    Java

    # Use the official maven/Java 8 image to create a build artifact: https://hub.docker.com/_/maven
    FROM maven:3.5-jdk-8-alpine as builder
    
    # Copy local code to the container image.
    WORKDIR /app
    COPY pom.xml .
    COPY src ./src
    
    # Build a release artifact.
    RUN mvn package -DskipTests
    
    # Use the Official OpenJDK image for a lean production stage of our multi-stage build.
    # https://hub.docker.com/_/openjdk
    # https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
    FROM openjdk:8-jre-alpine
    
    # 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", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/helloworld.jar"]
    

  2. בנה את תמונת המכולה שלך באמצעות Cloud Build על ידי הפעלת הפקודה הבאה מהספרייה המכילה את Dockerfile שלך:

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

    לאחר ההצלחה, תראה הודעת SUCCESS המכילה את שם התמונה
    ( gcr.io/ PROJECT_ID /helloworld ).

תמונת המכולה מאוחסנת כעת ב-Container Registry וניתן לעשות בה שימוש חוזר אם תרצה.

שים לב שבמקום Cloud Build, אתה יכול להשתמש בגרסה המותקנת מקומית של Docker כדי לבנות את הקונטיינר שלך באופן מקומי .

שלב 3 : פרוס את תמונת המכולה ל-Cloud Run

  1. פרוס באמצעות הפקודה הבאה:

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

  2. כאשר תתבקש:

לקבלת הביצועים הטובים ביותר, אתר את שירות Cloud Run שלך יחד עם אירוח באמצעות האזורים הבאים:

  • us-west1
  • us-central1
  • us-east1
  • europe-west1
  • asia-east1

שכתובים ל-Cloud Run מארח נתמכים באזורים הבאים:

  • asia-east1
  • asia-east2
  • asia-northeast1
  • asia-northeast2
  • asia-northeast3
  • asia-south1
  • asia-south2
  • asia-southeast1
  • asia-southeast2
  • australia-southeast1
  • australia-southeast2
  • europe-central2
  • europe-north1
  • europe-southwest1
  • europe-west1
  • europe-west12
  • europe-west2
  • europe-west3
  • europe-west4
  • europe-west6
  • europe-west8
  • europe-west9
  • me-central1
  • me-west1
  • northamerica-northeast1
  • northamerica-northeast2
  • southamerica-east1
  • southamerica-west1
  • us-central1
  • us-east1
  • us-east4
  • us-east5
  • us-south1
  • us-west1
  • us-west2
  • us-west3
  • us-west4
  • us-west1
  • us-central1
  • us-east1
  • europe-west1
  • asia-east1
  1. המתן מספר רגעים עד שהפריסה תושלם. לאחר הצלחה, שורת הפקודה מציגה את כתובת האתר של השירות. לדוגמה: https://helloworld- RANDOM_HASH -us-central1.a.run.app

  2. בקר בקונטיינר שנפרס על ידי פתיחת כתובת האתר של השירות בדפדפן אינטרנט.

השלב הבא ידריך אותך כיצד לגשת לאפליקציה המכולה הזו מכתובת אתר לאירוח של Firebase , כך שתוכל ליצור תוכן דינמי עבור האתר שלך שמתארח ב-Firebase.

שלב 4: הפנה בקשות אירוח לאפליקציה המכולה שלך

עם כללי כתיבה מחדש , אתה יכול להפנות בקשות התואמות דפוסים ספציפיים ליעד יחיד.

הדוגמה הבאה מראה כיצד להפנות את כל הבקשות מהדף /helloworld באתר האחסון שלך כדי להפעיל את ההפעלה וההפעלה של מופע המכולה helloworld שלך.

  1. תוודא ש:

    להנחיות מפורטות לגבי התקנת ה-CLI ואתחול האחסון, עיין במדריך התחל לאירוח .

  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

כעת ניתן להגיע למאגר שלך באמצעות כתובות האתרים הבאות:

בקר בדף תצורת אירוח לפרטים נוספים על כללי כתיבה מחדש . אתה יכול גם ללמוד על סדר העדיפות של התגובות עבור תצורות אירוח שונות.

בדיקה מקומית

במהלך הפיתוח, אתה יכול להפעיל ולבדוק את תמונת המכולה שלך באופן מקומי. להנחיות מפורטות, בקר בתיעוד של Cloud Run .

הצעדים הבאים