在 App Engine 彈性環境中建立 Go 應用程式

區域 ID

REGION_ID 是 Google 根據您建立應用程式時選取的區域指派的縮寫代碼。即使部分區域 ID 看似常用國家/地區和省份代碼,但該代碼並不對應國家/地區或省份。如果是 2020 年 2 月後建立的應用程式,App Engine 網址會包含 REGION_ID.r。如果是這段時間前建立的現有應用程式,網址可選擇是否包含區域 ID。

進一步瞭解區域 ID。

本快速入門導覽課程將示範如何建立及部署應用程式,顯示簡短訊息。您可以在 app.yaml 檔案中指定執行階段版本和作業系統,將本快速入門導覽課程中的範例應用程式用於任何支援的 Go 版本。

事前準備

  1. 登入 Google Cloud 帳戶。如果您是 Google Cloud新手,歡迎 建立帳戶,親自體驗產品的實際應用成效。新客戶還能獲得價值 $300 美元的免費抵免額,能用於執行、測試及部署工作負載。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Build API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Cloud Build API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. To initialize the gcloud CLI, run the following command:

    gcloud init

必要的角色

如要取得完成本快速入門導覽課程所需的權限,請要求管理員授予您下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

其他必要條件

  1. 使用您的專案將 App Engine 應用程式初始化,然後選擇地區:

    gcloud app create --project=[YOUR_PROJECT_ID]
    

    系統提示時,請選取要放置 App Engine 應用程式的區域。

  2. 在本機電腦上安裝下列項目:

    • 執行以下指令,安裝 gcloud 元件 (包括 Go 適用的 App Engine 擴充功能):

      gcloud components install app-engine-go
      

App Engine 位置

App Engine 具有區域性,這表示執行您應用程式的基礎架構位於特定區域,並由 Google 負責管理,實現該區域內所有可用區之間的備援可用性。

選擇應用程式執行所在區域時,主要考量因素是延遲時間、可用性或耐久性方面的需求。原則上可以選擇距離應用程式使用者最近的區域,但也應考慮 App Engine 的可用地區,以及應用程式所用其他Google Cloud 產品和服務的位置。如果跨多個位置使用服務,可能會影響應用程式的延遲時間和定價。

應用程式的地區設定完成後即無法更改。

如果您已建立 App Engine 應用程式,可以透過下列任一方式查看其區域:

本快速入門導覽課程假設您已熟悉 Go 程式設計語言,並且已在系統上安裝 Go。

下載 Hello World 應用程式

我們已預先建立 App Engine 適用的 Hello World 應用程式,方便您快速瞭解如何在 Google Cloud部署應用程式。

  1. 將 Hello World 範例應用程式存放區複製到本機電腦。

    git clone https://github.com/GoogleCloudPlatform/golang-samples
    

  2. 變更為包含程式碼範例的目錄。

       cd golang-samples/appengine_flexible/helloworld
    

在本機電腦上執行 Hello World

在本機電腦上執行 Hello World 應用程式:

  1. 啟動本機網路伺服器。

    go run *.go
    
  2. 在網路瀏覽器中,輸入下列網址:

    http://localhost:8080

    如果您使用 Cloud Shell,請在工具列中點選「網頁預覽」,然後選取「透過以下通訊埠預覽:8080」。

此時頁面會顯示來自範例應用程式的「Hello World」訊息。請在終端機視窗中,按下 Ctrl+C 鍵來關閉網路伺服器。

在 App Engine 上部署並執行 Hello World

如要將您的應用程式部署到 App Engine 彈性環境:

  1. 從 helloworld 目錄執行下列指令,部署 Hello World 應用程式:

    gcloud app deploy

    瞭解選用標記。

    常見的 gcloud 指令標記

    • 加上 --version 標記以指定專門用來辨識您應用程式版本的 ID。如未指定,將由系統自動產生,例如:--version [YOUR_VERSION_ID]
    • 加入 --project 標記,指定要用於 gcloud 工具的替代 Google Cloud 專案 ID (而非您初始化為預設值的 ID)。示例: --project [YOUR_PROJECT_ID]

    範例:

    gcloud app deploy --version pre-prod-5 --project my-sample-app

    如要進一步瞭解如何透過指令列部署應用程式,請參閱測試及部署您的應用程式。如需所有指令標記的清單,請參閱 gcloud app deploy 參考資料。

  2. 啟動瀏覽器,在以下網址查看應用程式: https://PROJECT_ID.REGION_ID.r.appspot.com

    gcloud app browse
    ,其中 PROJECT_ID 代表您的 Google Cloud專案 ID。

此時,顯示 Hello World 訊息的頁面是由在 App Engine 執行個體上運作的網路伺服器提供。

恭喜!您已將第一個 App Engine 應用程式部署至 App Engine 彈性環境!

如果在部署應用程式時發生任何錯誤,請參閱疑難排解提示。

請參閱下列各節,瞭解清除所用資源的資訊,並取得相關後續步驟的連結。

清除所用資源

如要避免產生費用,您可以刪除 Google Cloud 專案,這樣一來,系統就會停止對該專案中使用的所有資源計費。

  1. 前往 Google Cloud 控制台的「Manage resources」(管理資源) 頁面。

    前往「Manage resources」(管理資源)

  2. 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)。
  3. 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。

後續步驟

瞭解整個平台

現在您已瞭解如何開發及部署 App Engine 應用程式,可以繼續探索 Google Cloud。您已安裝 Google Cloud CLI,可透過這項工具與 Cloud SQL、Cloud Storage、Firestore 等產品互動。

瞭解 App Engine 彈性環境

以下是一些可協助您瞭解 App Engine 的主題:

Hello World 程式碼審查

Hello World 是再簡單不過的 App Engine 應用程式,只包含一項服務、只有一種版本,且所有程式碼都位於應用程式的根目錄中。本節將詳細說明每個應用程式檔案。

helloworld.go

helloworld.go 檔案會註冊接聽 / 要求的處理常式,並以「Hello world!」訊息回應。


package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	http.HandleFunc("/", handle)
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("Listening on port %s", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}

func handle(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	fmt.Fprint(w, "Hello world!")
}

app.yaml

app.yaml 檔案說明應用程式的下列設定:

  • 設定 env: flex,指出應用程式使用 App Engine 彈性環境。
  • 指定應用程式使用的執行階段。

    # Copyright 2019 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #     https://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    runtime: go
    env: flex
    
    runtime_config:
      operating_system: 'ubuntu22'
      runtime_version: 1.25
    # This sample incurs costs to run on the App Engine flexible environment. 
    # The settings below are to reduce costs during testing and are not appropriate
    # for production use. For more information, see:
    # https://docs.cloud.google.com/appengine/docs/flexible/go/configuring-your-app-with-app-yaml
    manual_scaling:
      instances: 1
    resources:
      cpu: 1
      memory_gb: 0.5
      disk_size_gb: 10