建立公開運作時間檢查

本文說明如何建立公開運作時間檢查。 公開運作時間檢查可從世界各地的多個位置,向公開網址或 Google Cloud 資源發出要求,確認資源是否會回應。如要瞭解如何為私人網路建立運作時間檢查,請參閱建立私人運作時間檢查

公開運作時間檢查可判斷下列受監控資源的可用性:

如要查看管理及監控運作時間檢查的相關資訊連結,請參閱本文的「後續步驟」一節。

這項功能僅支援 Google Cloud 專案。 如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。

關於運作時間檢查

如果是 HTTP 和 HTTPS,系統會追蹤所有網址重新導向,並使用運作時間檢查收到的最終回應來評估任何成功標準。如果是 HTTPS 檢查,系統會根據最終回應中收到的伺服器憑證,計算 SSL 憑證的到期時間。

運作時間檢查必須符合下列條件,才會成功:

  • HTTP 狀態必須符合您指定的條件。
  • 回覆資料沒有必要內容,或存在必要內容。

運作時間檢查不會載入頁面資產或執行 JavaScript,且運作時間檢查的預設設定不包含驗證。

事前準備

在將儲存運作時間檢查的 Google Cloud 專案中,完成下列步驟:

  1. 如要取得建立正常運作時間檢查所需的權限,請要求管理員授予您專案的下列 IAM 角色:

    • Monitoring 編輯者 (roles/monitoring.editor) - Google Cloud 控制台使用者
    • Monitoring 運作時間檢查設定編輯者 (roles/monitoring.uptimeCheckConfigEditor) - API 使用者
    • Monitoring AlertPolicy 編輯者 (roles/monitoring.alertPolicyEditor) - API 使用者
    • Monitoring NotificationChannel 編輯者 (roles/monitoring.notificationChannelEditor) - API 使用者

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

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

  2. 確認要檢查的資源具有公開端點,或位於可設定的防火牆後方。

    如為其他設定,則必須建立私人運作時間檢查。 詳情請參閱「建立私人運作時間檢查」。

  3. 如果資源受到防火牆保護,請將防火牆設定為允許來自運作時間檢查伺服器 IP 位址的連入流量。詳情請參閱「列出運作時間檢查伺服器 IP 位址」。

  4. 設定要用來接收通知的通知管道。建議您建立多種通知管道,詳情請參閱「建立及管理通知管道」。

  5. 為運作時間檢查找出至少三位檢查員。 運作時間檢查區域 USA 包含 USA_OREGONUSA_IOWAUSA_VIRGINIA 區域。每個USA_*區域都有一個檢查員,USA則包含所有三個區域。其他正常運作時間檢查區域 (EUROPESOUTH_AMERICAASIA_PACIFIC) 各有一個檢查程式。

    使用 Google Cloud 控制台時,如果選取「全域」,或使用 API 時選取 REGION_UNSPECIFIED,系統就會從所有運作時間檢查區域發出運作時間檢查。

  6. Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

      In the Google Cloud console, activate Cloud Shell.

      Activate Cloud Shell

      At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

      Terraform

      如要在本機開發環境中使用本頁的 Terraform 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

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

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

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      C#

      如要在本機開發環境中使用本頁的 .NET 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

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

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

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Go

      如要在本機開發環境中使用本頁的 Go 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

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

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

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Java

      如要在本機開發環境中使用本頁的 Java 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

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

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

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Node.js

      如要在本機開發環境中使用本頁的 Node.js 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

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

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

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      PHP

      如要在本機開發環境中使用本頁的 PHP 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

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

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

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Python

      如要在本機開發環境中使用本頁的 Python 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

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

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

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Ruby

      如要在本機開發環境中使用本頁的 Ruby 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

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

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

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      REST

      如要在本機開發環境中使用本頁的 REST API 範例,請使用您提供給 gcloud CLI 的憑證。

        After installing the Google Cloud CLI, initialize it by running the following command:

        gcloud init

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

      詳情請參閱 Google Cloud 驗證說明文件中的「Authenticate for using REST」。

      建立運作時間檢查

      本節說明如何建立及設定運作時間檢查。

      如要為已設定至少一個 TCP 或 HTTP/S 連接埠的外部負載平衡器建立運作時間檢查,請按照下列操作說明進行。或者,您也可以前往服務的「服務詳細資料」頁面,然後點選「建立運作時間檢查」。如果從「服務詳細資料」頁面開始,系統會預先填入服務專屬欄位。

      控制台

      如要使用 Google Cloud 控制台建立運作時間檢查,請按照下列步驟操作:

      1. 前往 Google Cloud 控制台的「運作時間檢查」頁面:

        前往「Uptime checks」(運作時間檢查)

        如果您是使用搜尋列尋找這個頁面,請選取子標題為「Monitoring」的結果

      2. 在 Google Cloud 控制台的工具列中,選取您的 Google Cloud 專案。如為「App Hub」設定,請選取 App Hub 主機專案或已啟用應用程式的資料夾管理專案。
      3. 按一下「建立運作時間檢查」

        建立運作時間檢查對話方塊。

      4. 指定運作時間檢查的目標:

        1. 選取通訊協定。您可以選取「HTTP」、「HTTPS」或「TCP」

        2. 選擇下列其中一種資源類型:

          • [URL] (網址):任何 IPv4 位址或主機名稱。路徑與通訊埠需分開輸入。
          • Kubernetes LoadBalancer Service:LoadBalancer 類型的 Kubernetes 服務。
          • 執行個體:Compute Engine 或 AWS EC2 執行個體。
          • [App Engine]:App Engine 應用程式 (模組)。
          • [Elastic Load Balancer] (彈性負載平衡器):AWS 負載平衡器。
        3. 輸入通訊協定專屬欄位:

          • 如果是 TCP 檢查,請輸入通訊埠。

          • 針對 HTTP 和 HTTPS 檢查,您可以輸入主機或資源內的路徑。使用這些通訊協定的所有運作時間檢查都會向 http://target/path傳送要求。在這個運算式中,如果是網址資源,target 是主機名稱或 IP 位址。如果是 App Engine 資源,target 是從服務名稱衍生而來的主機名稱。以執行個體和負載平衡器資源為例,target 是從您為資源或資源群組提供的名稱衍生而來的 IP 位址。

            如果將 path 欄位留空或將值設為 /,系統就會向 http://target/ 發出要求。

            舉例來說,如要對網址資源 example.com/tester 發出運作時間檢查,請將「Hostname」(主機名稱) 欄位設為 example.com,並將「Path」(路徑) 欄位設為 /tester

            假設您已將伺服器部署至 App Engine,且該伺服器具有支援 //hello 的調度器。如要將運作時間檢查發給「/」處理常式,請將「Path」(路徑) 欄位留空。如要向 /hello 處理常式發出正常運作時間檢查,請將「Path」欄位的值設為 /hello

        4. 輸入資源專屬欄位:

          • 如果是「網址」資源,請在「主機名稱」欄位中輸入主機名稱。例如輸入 example.com

          • 如果是 App Engine 資源,請在「服務」欄位中輸入服務名稱。

          • 如果是 Elastic Load BalancerInstance 資源,請按照下列方式填寫「適用於」欄位:

            • 如要對單一執行個體或負載平衡器發出正常運作時間檢查,請選取「單一」,然後使用選單選取特定執行個體或負載平衡器。
            • 如要對監控群組發出運作時間檢查,請選取「群組」,然後使用選單選取群組名稱。
        5. 選用:如要設定運作時間檢查的執行頻率,請使用「檢查頻率」欄位。

        6. 選用:如要選取檢查程式區域,或設定 HTTP 和 HTTPS 檢查的 SSL 憑證、驗證、標頭和通訊埠,請按一下「更多目標選項」

          • 「Regions」(區域):選取運作時間檢查要接收要求的區域。運作時間檢查至少要有三個檢查程式。 除了美國有三位檢查員外,其他地區都只有一位檢查員。預設設定為「全球」,包含所有區域。
          • ICMP Ping:設定運作時間檢查,最多可傳送三個 Ping。詳情請參閱「使用 ICMP Ping」。
          • 要求方法:如果是 HTTP 檢查,請選取要求方法。
          • 主體:如要進行 HTTP POST 檢查,請輸入網址編碼主體,您必須自行編碼。其他檢查請將這個欄位留空。
          • 主機標頭:填入此欄位可檢查虛擬主機。 這個欄位不適用於 TCP 檢查。
          • 「Port」(通訊埠):指定通訊埠編號。
          • 「Custom Headers」(自訂標頭):提供自訂標頭,並視需要進行加密。加密後,表單中會隱藏標頭的值。如果您不希望其他人看到驗證相關的標頭,可以使用加密功能。
          • 驗證:這些值會以 Authorization 標頭的形式傳送。這個欄位不適用於 TCP 檢查。

            選擇下列任一選項:

            • 基本驗證:提供單一使用者名稱和密碼。表單中將一律隱藏密碼。
            • 服務代理驗證:啟用後,系統會為監控服務代理產生身分權杖。這個選項僅適用於 HTTPS 檢查。
          • SSL 憑證驗證:如果您為網址資源選取 HTTPS,服務預設會嘗試透過 HTTPS 連線,並驗證 SSL 憑證。如果網址的憑證無效,運作時間檢查就會失敗。憑證無效的原因包括:

            • 過期憑證
            • 自行簽署的憑證
            • 網域名稱不符的憑證
            • 使用授權單位資訊存取權 (AIA) 擴充功能的憑證。

            如要強制執行 HTTPS 正常運作時間檢查來驗證 SSL 憑證,請選取「驗證 SSL 憑證」

            如要停用 SSL 憑證驗證,請清除「驗證 SSL 憑證」

            如果您的 SSL 憑證有 AIA 擴充功能,就必須停用 SSL 憑證驗證。系統不支援這類憑證,因此驗證程序會失敗。一般來說,錯誤訊息是「Responded with SSL handshake Error in 10000 ms」。

            您可以透過這項指標monitoring.googleapis.com/uptime_check/time_until_ssl_cert_expires建立快訊政策,在憑證到期前收到通知。詳情請參閱「範例政策:運作時間檢查政策」。

            選取「驗證 SSL 憑證」核取方塊。

      5. 按一下「繼續」,然後設定回覆規定。 這個部分的所有設定都有預設值:

        • 如要變更運作時間檢查的逾時時間,請使用「回應逾時」欄位。如果在這段期間內,運作時間檢查未從多個位置收到回應,就會失敗。

        • 如要設定運作時間檢查來執行內容比對,請確認切換按鈕標籤為「已啟用內容比對功能」

          • 從選項選單中選取「回應內容比對類型」。 這個欄位會決定如何比較回應內容與傳回的資料。舉例來說,假設回應內容為 abcd,且內容比對類型為「包含」。只有在回應資料包含 abcd 時,運作時間檢查才會成功。詳情請參閱「驗證回應資料」。
          • 輸入回覆內容。回應內容必須是字串,且長度不得超過 1024 個位元組。在 API 中,這個欄位是 ContentMatcher 物件。
        • 如要避免因運作時間檢查而建立記錄項目,請清除「記錄失敗的檢查項目」

        • 如果是 HTTP 運作時間檢查,請設定可接受的回應代碼。 根據預設,HTTP 運作時間檢查會將任何 2xx 回應標示為成功回應。

      6. 按一下「繼續」,然後設定通知。

        如要在運作時間檢查失敗時收到通知,請建立快訊政策,並為該政策設定通知管道

        1. 選用:更新快訊政策的名稱。
        2. 選用:在「Duration」(時間長度) 欄位中,選取運作時間檢查必須失敗多久後才會傳送通知。根據預設,如果至少兩個區域回報運作時間檢查失敗,且持續至少一分鐘,系統就會傳送通知。
        3. 在標示為「通知管道」的方塊中,按一下「選單」,選取要新增的管道,然後按一下「確定」

          選單中的通知管道會依管道類型分組,並按字母順序排序。

        如不想建立快訊政策,請確認切換按鈕的文字為「不建立警告」

      7. 按一下「繼續」,然後完成運作時間檢查:

        1. 輸入運作時間檢查的描述性名稱。

        2. 選用:如要為運作時間檢查新增使用者定義的標籤,請執行下列操作:

          1. 按一下 「顯示使用者標籤」
          2. 在「Key」(鍵) 欄位中,輸入標籤名稱。 標籤名稱的開頭須為小寫英文字母,可包含小寫英文字母、數字、底線和破折號。例如,輸入 severity
          3. 在「值」欄位中,輸入標籤的值。標籤值可包含小寫字母、數字、底線和破折號。例如,輸入 critical
          4. 如要新增其他標籤,請按一下「新增使用者標籤」,然後輸入標籤的鍵和值。
        3. 如要驗證運作時間檢查設定,請按一下「測試」。 如果結果與您的期望不符,請參閱「檢查失敗」一節,更正設定,然後重複執行驗證步驟。

        4. 按一下「建立」,如果您選取「建立」,但未填寫必填欄位,系統就會顯示錯誤訊息。

      gcloud

      如要建立運作時間檢查,請執行 gcloud monitoring uptime create 指令:

      gcloud monitoring uptime create DISPLAY_NAME REQUIRED_FLAGS OPTIONAL_FLAGS --project=PROJECT_ID
      

      執行上一個指令前,請先取代下列項目:

      • PROJECT_ID:專案的 ID。如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。

      • DISPLAY_NAME:運作時間檢查的名稱。

      • REQUIRED_FLAGS:設定要由正常運作時間檢查探測的資源。舉例來說,下列指令會建立正常運作時間檢查,針對特定專案測試網址 EXAMPLE.com

        gcloud monitoring uptime create DISPLAY_NAME \
        --resource-labels=host=EXAMPLE.com,project_id=PROJECT_ID \
        --resource-type=uptime-url
        

        先前的指令會為資源類型 uptime-url 要求的每個標籤指定值。

      • OPTIONAL_FLAGS:設定這些標記來覆寫預設值。舉例來說,如果通訊協定不是 http,您就必須設定 --protocol 標記。

      Terraform

      如要瞭解如何套用或移除 Terraform 設定,請參閱「基本 Terraform 指令」。 詳情請參閱 Terraform供應商參考說明文件

      如要建立運作時間檢查和快訊政策來監控該檢查,請按照下列步驟操作:

      1. 安裝及設定 Terraform,如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。
      2. 編輯 Terraform 設定檔,新增 google_monitoring_uptime_check_config 資源,然後套用設定檔。

        以下範例說明如何設定檢查公開網址:

        resource "google_monitoring_uptime_check_config" "example" {
            display_name = "example"
            timeout      = "60s"
        
            http_check {
                port = "80"
                request_method = "GET"
            }
        
            monitored_resource {
                type = "uptime_url"
                labels = {
                    project_id = "PROJECT_ID"
                    host="EXAMPLE.com"
                }
            }
        
            checker_type = "STATIC_IP_CHECKERS"
        }
        

        在上述運算式中:

        • PROJECT_ID 是專案 ID。如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。
        • EXAMPLE.com 是主機網址。
      3. 選用:建立通知管道和快訊政策:

        下列步驟會使用 Google Cloud 主控台建立通知管道和快訊政策。這個方法可確保快訊政策只會監控運作時間檢查產生的資料。

        1. 如要建立通知管道,請按照下列步驟操作:

          1. 前往 Google Cloud 控制台的 「Alerting」(警告) 頁面

            前往「Alerting」(快訊)

            如果您是使用搜尋列尋找這個頁面,請選取子標題為「Monitoring」的結果

          2. 在 Google Cloud 控制台的工具列中,選取您的 Google Cloud 專案。如為「App Hub」設定,請選取 App Hub 主機專案或已啟用應用程式的資料夾管理專案。
          3. 選取「管理通知管道」
          4. 前往要新增的管道類型,按一下「新增」,然後完成對話方塊。
        2. 如要建立快訊政策,請按照下列指示操作:

          1. 前往 Google Cloud 控制台的「運作時間檢查」頁面:

            前往「Uptime checks」(運作時間檢查)

            如果您是使用搜尋列尋找這個頁面,請選取子標題為「Monitoring」的結果

          2. 在 Google Cloud 控制台的工具列中,選取您的 Google Cloud 專案。如為「App Hub」設定,請選取 App Hub 主機專案或已啟用應用程式的資料夾管理專案。
          3. 找出運作時間檢查,選取「更多」,然後選取「新增快訊政策」
          4. 在對話方塊中,前往「通知和名稱」部分,展開「通知管道」,然後進行選取。
          5. 為快訊政策命名,然後按一下「建立政策」

        如要建立快訊政策,請在設定檔中新增 google_monitoring_alert_policy 資源,然後套用新設定。

      C#

      如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

      public static object CreateUptimeCheck(string projectId, string hostName,
          string displayName)
      {
          // Define a new config.
          var config = new UptimeCheckConfig()
          {
              DisplayName = displayName,
              MonitoredResource = new MonitoredResource()
              {
                  Type = "uptime_url",
                  Labels = { { "host", hostName } }
              },
              HttpCheck = new UptimeCheckConfig.Types.HttpCheck()
              {
                  Path = "/",
                  Port = 80,
              },
              Timeout = TimeSpan.FromSeconds(10).ToDuration(),
              Period = TimeSpan.FromMinutes(5).ToDuration()
          };
          // Create a client.
          var client = UptimeCheckServiceClient.Create();
          ProjectName projectName = new ProjectName(projectId);
          // Create the config.
          var newConfig = client.CreateUptimeCheckConfig(
              projectName,
              config,
              CallSettings.FromExpiration(
                  Expiration.FromTimeout(
                      TimeSpan.FromMinutes(2))));
          Console.WriteLine(newConfig.Name);
          return 0;
      }
      

      Java

      如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

      private static void createUptimeCheck(
          String projectId, String displayName, String hostName, String pathName) throws IOException {
        CreateUptimeCheckConfigRequest request =
            CreateUptimeCheckConfigRequest.newBuilder()
                .setParent(ProjectName.format(projectId))
                .setUptimeCheckConfig(
                    UptimeCheckConfig.newBuilder()
                        .setDisplayName(displayName)
                        .setMonitoredResource(
                            MonitoredResource.newBuilder()
                                .setType("uptime_url")
                                .putLabels("host", hostName))
                        .setHttpCheck(HttpCheck.newBuilder().setPath(pathName).setPort(80))
                        .setTimeout(Duration.newBuilder().setSeconds(10))
                        .setPeriod(Duration.newBuilder().setSeconds(300)))
                .build();
        try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
          UptimeCheckConfig config = client.createUptimeCheckConfig(request);
          System.out.println("Uptime check created: " + config.getName());
        } catch (Exception e) {
          usage("Exception creating uptime check: " + e.toString());
          throw e;
        }
      }

      Go

      如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

      
      // createGet creates an example uptime check on a GET request.
      func createGet(w io.Writer, projectID string) (*monitoringpb.UptimeCheckConfig, error) {
      	ctx := context.Background()
      	client, err := monitoring.NewUptimeCheckClient(ctx)
      	if err != nil {
      		return nil, fmt.Errorf("NewUptimeCheckClient: %w", err)
      	}
      	defer client.Close()
      	req := &monitoringpb.CreateUptimeCheckConfigRequest{
      		Parent: "projects/" + projectID,
      		UptimeCheckConfig: &monitoringpb.UptimeCheckConfig{
      			DisplayName: "new GET uptime check",
      			Resource: &monitoringpb.UptimeCheckConfig_MonitoredResource{
      				MonitoredResource: &monitoredres.MonitoredResource{
      					Type: "uptime_url",
      					Labels: map[string]string{
      						"host": "example.com",
      					},
      				},
      			},
      			CheckRequestType: &monitoringpb.UptimeCheckConfig_HttpCheck_{
      				HttpCheck: &monitoringpb.UptimeCheckConfig_HttpCheck{
      					RequestMethod: monitoringpb.UptimeCheckConfig_HttpCheck_GET,
      					Path:          "/",
      					Port:          80,
      				},
      			},
      			Timeout: &duration.Duration{Seconds: 10},
      			Period:  &duration.Duration{Seconds: 300},
      		},
      	}
      	config, err := client.CreateUptimeCheckConfig(ctx, req)
      	if err != nil {
      		return nil, fmt.Errorf("CreateUptimeCheckConfig GET: %w", err)
      	}
      	fmt.Fprintf(w, "Successfully created GET uptime check %q\n", config.GetDisplayName())
      	return config, nil
      }
      
      // createPost creates an example uptime check on a POST request.
      func createPost(w io.Writer, projectID string) (*monitoringpb.UptimeCheckConfig, error) {
      	ctx := context.Background()
      	client, err := monitoring.NewUptimeCheckClient(ctx)
      	if err != nil {
      		return nil, fmt.Errorf("NewUptimeCheckClient: %w", err)
      	}
      	defer client.Close()
      	req := &monitoringpb.CreateUptimeCheckConfigRequest{
      		Parent: "projects/" + projectID,
      		UptimeCheckConfig: &monitoringpb.UptimeCheckConfig{
      			DisplayName: "new POST uptime check",
      			Resource: &monitoringpb.UptimeCheckConfig_MonitoredResource{
      				MonitoredResource: &monitoredres.MonitoredResource{
      					Type: "uptime_url",
      					Labels: map[string]string{
      						"host": "example.com",
      					},
      				},
      			},
      			CheckRequestType: &monitoringpb.UptimeCheckConfig_HttpCheck_{
      				HttpCheck: &monitoringpb.UptimeCheckConfig_HttpCheck{
      					RequestMethod: monitoringpb.UptimeCheckConfig_HttpCheck_POST,
      					ContentType:   monitoringpb.UptimeCheckConfig_HttpCheck_URL_ENCODED,
      					Path:          "/",
      					Port:          80,
      					Body:          []byte(base64.URLEncoding.EncodeToString([]byte("key: value"))),
      				},
      			},
      			Timeout: &duration.Duration{Seconds: 10},
      			Period:  &duration.Duration{Seconds: 300},
      		},
      	}
      	config, err := client.CreateUptimeCheckConfig(ctx, req)
      	if err != nil {
      		return nil, fmt.Errorf("CreateUptimeCheckConfig POST: %w", err)
      	}
      	fmt.Fprintf(w, "Successfully created POST uptime check %q\n", config.GetDisplayName())
      	return config, nil
      }
      

      Node.js

      如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

      // Imports the Google Cloud client library
      const monitoring = require('@google-cloud/monitoring');
      
      // Creates a client
      const client = new monitoring.UptimeCheckServiceClient();
      
      /**
       * TODO(developer): Uncomment and edit the following lines of code.
       */
      // const projectId = 'YOUR_PROJECT_ID';
      // const hostname = 'mydomain.com';
      
      const request = {
        // i.e. parent: 'projects/my-project-id'
        parent: client.projectPath(projectId),
        uptimeCheckConfig: {
          displayName: 'My Uptime Check',
          monitoredResource: {
            // See the Uptime Check docs for supported MonitoredResource types
            type: 'uptime_url',
            labels: {
              host: hostname,
            },
          },
          httpCheck: {
            path: '/',
            port: 80,
          },
          timeout: {
            seconds: 10,
          },
          period: {
            seconds: 300,
          },
        },
      };
      
      // Creates an uptime check config for a GCE instance
      const [uptimeCheckConfig] = await client.createUptimeCheckConfig(request);
      console.log('Uptime check created:');
      console.log(`ID: ${uptimeCheckConfig.name}`);
      console.log(`Display Name: ${uptimeCheckConfig.displayName}`);
      console.log('Resource: %j', uptimeCheckConfig.monitoredResource);
      console.log('Period: %j', uptimeCheckConfig.period);
      console.log('Timeout: %j', uptimeCheckConfig.timeout);
      console.log(`Check type: ${uptimeCheckConfig.check_request_type}`);
      console.log(
        'Check: %j',
        uptimeCheckConfig.httpCheck || uptimeCheckConfig.tcpCheck
      );
      console.log(
        `Content matchers: ${uptimeCheckConfig.contentMatchers
          .map(matcher => matcher.content)
          .join(', ')}`
      );
      console.log(`Regions: ${uptimeCheckConfig.selectedRegions.join(', ')}`);
      

      PHP

      如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

      use Google\Api\MonitoredResource;
      use Google\Cloud\Monitoring\V3\Client\UptimeCheckServiceClient;
      use Google\Cloud\Monitoring\V3\CreateUptimeCheckConfigRequest;
      use Google\Cloud\Monitoring\V3\UptimeCheckConfig;
      
      /**
       * Example:
       * ```
       * create_uptime_check($projectId, 'myproject.appspot.com', 'Test Uptime Check!');
       * ```
       *
       * @param string $projectId Your project ID
       * @param string $hostName
       * @param string $displayName
       */
      function create_uptime_check($projectId, $hostName = 'example.com', $displayName = 'New uptime check')
      {
          $projectName = 'projects/' . $projectId;
          $uptimeCheckClient = new UptimeCheckServiceClient([
              'projectId' => $projectId,
          ]);
      
          $monitoredResource = new MonitoredResource();
          $monitoredResource->setType('uptime_url');
          $monitoredResource->setLabels(['host' => $hostName]);
      
          $uptimeCheckConfig = new UptimeCheckConfig();
          $uptimeCheckConfig->setDisplayName($displayName);
          $uptimeCheckConfig->setMonitoredResource($monitoredResource);
          $createUptimeCheckConfigRequest = (new CreateUptimeCheckConfigRequest())
              ->setParent($projectName)
              ->setUptimeCheckConfig($uptimeCheckConfig);
      
          $uptimeCheckConfig = $uptimeCheckClient->createUptimeCheckConfig($createUptimeCheckConfigRequest);
      
          printf('Created an uptime check: %s' . PHP_EOL, $uptimeCheckConfig->getName());
      }

      Python

      如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

      def create_uptime_check_config_get(
          project_id: str, host_name: str = None, display_name: str = None
      ) -> uptime.UptimeCheckConfig:
          """Creates a new uptime check configuration
      
          Args:
              project_id: Google Cloud project id where the uptime check is created
              host_name: An example label's value for the "host" label
              display_name: A human friendly name of the configuration
      
          Returns:
              A structure that describes a new created uptime check
          """
          config = monitoring_v3.UptimeCheckConfig()
          config.display_name = display_name or "New GET uptime check"
          config.monitored_resource = {
              "type": "uptime_url",
              "labels": {"host": host_name or "example.com"},
          }
          config.http_check = {
              "request_method": monitoring_v3.UptimeCheckConfig.HttpCheck.RequestMethod.GET,
              "path": "/",
              "port": 80,
          }
          config.timeout = {"seconds": 10}
          config.period = {"seconds": 300}
      
          client = monitoring_v3.UptimeCheckServiceClient()
          new_config = client.create_uptime_check_config(
              request={"parent": project_id, "uptime_check_config": config}
          )
          pprint.pprint(new_config)
          return new_config
      
      
      def create_uptime_check_config_post(
          project_id: str, host_name: str = None, display_name: str = None
      ) -> uptime.UptimeCheckConfig:
          """Creates a new uptime check configuration
      
          Args:
              project_id: Google Cloud project id where the uptime check is created
              host_name: An example label's value for the "host" label
              display_name: A human friendly name of the configuration
      
          Returns:
              A structure that describes a new created uptime check
          """
          config = monitoring_v3.UptimeCheckConfig()
          config.display_name = display_name or "New POST uptime check"
          config.monitored_resource = {
              "type": "uptime_url",
              "labels": {"host": host_name or "example.com"},
          }
          config.http_check = {
              "request_method": monitoring_v3.UptimeCheckConfig.HttpCheck.RequestMethod.POST,
              "content_type": monitoring_v3.UptimeCheckConfig.HttpCheck.ContentType.URL_ENCODED,
              "body": "foo=bar".encode("utf-8"),
              "path": "/",
              "port": 80,
          }
          config.timeout = {"seconds": 10}
          config.period = {"seconds": 300}
      
          client = monitoring_v3.UptimeCheckServiceClient()
          new_config = client.create_uptime_check_config(
              request={"parent": project_id, "uptime_check_config": config}
          )
          pprint.pprint(new_config)
          return new_config
      
      

      Ruby

      如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

      gem "google-cloud-monitoring"
      require "google/cloud/monitoring"
      
      def create_uptime_check_config project_id: nil, host_name: nil, display_name: nil
        client = Google::Cloud::Monitoring.uptime_check_service
        project_name = client.project_path project: project_id
        config = {
          display_name:       display_name.nil? ? "New uptime check" : display_name,
          monitored_resource: {
            type:   "uptime_url",
            labels: { "host" => host_name.nil? ? "example.com" : host_name }
          },
          http_check:         { path: "/", port: 80 },
          timeout:            { seconds: 10 },
          period:             { seconds: 300 }
        }
        new_config = client.create_uptime_check_config \
          parent:              project_name,
          uptime_check_config: config
        puts new_config.name
        new_config
      end

      REST

      如要建立運作時間檢查,請呼叫 projects.uptimeCheckConfigs.create 方法。如下設定方法的參數:

      • 父項:必填。要建立運作時間檢查的專案。 如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。這個欄位的格式如下:

        projects/PROJECT_ID
        
      • 要求主體必須包含新運作時間檢查的 UptimeCheckConfig 物件。本頁面提供幾個欄位的相關資訊。如需這個物件及其欄位的完整說明文件,請參閱 UptimeCheckConfig

        • 請將設定物件的 name 欄位保留空白。系統建構回應設定物件時,會設定這個欄位。

        • 如果您要設定 HTTP 或 HTTPS 檢查,則必須填入 UptimeCheckConfig 物件的 HttpCheck 欄位。在這個物件中,將 requestMethod 欄位設為 GETPOST。如果省略這個欄位或設為 METHOD_UNSPECIFIED,系統就會發出 GET 要求。

          如果您要設定 POST 要求,請填寫 contentType、選用的 customContentTypebody 欄位。

      create 方法會傳回新設定的 UptimeCheckConfig 物件。

      如果建立的運作時間設定未如預期運作,請參閱本頁面的「檢查失敗」一節。

      運作時間檢查結果開始流入 Monitoring 之前,可能會有長達 5 分鐘的延遲。在該期間,運作時間檢查資訊主頁會將狀態回報為「no data available」(目前沒有任何可用資料)。

      使用 ICMP Ping

      為協助排解公開運作時間檢查失敗的問題,您可以設定運作時間檢查,在檢查期間傳送最多 3 個 ICMP Ping。舉例來說,如果應用程式發生逾時問題,或是網路連線發生問題,您都可以透過 Ping 判斷失敗原因。

      根據預設,運作時間檢查不會傳送 Ping。每次 Ping 都會增加運作時間檢查的延遲時間。私人運作時間檢查無法傳送 Ping。

      如果公開運作時間檢查失敗,系統會將 Ping 結果寫入 Cloud Logging 記錄檔。如果 Ping 失敗,系統會在記錄項目的 httpRequest 欄位中新增下列欄位:

      • rtt_usec:每個失敗的 Ping 要求的來回時間。
      • unreachable_count:傳回狀態碼 ICMP_DEST_UNREACH 的 Ping 要求數量。
      • no_answer_count:逾時且未傳回任何回應的 Ping 要求數量。

      系統不會記錄運作時間檢查成功的連線偵測 (ping) 結果。

      設定 Ping

      每項運作時間檢查設定都包含 HttpCheck 物件或 TcpCheck 物件。這兩個物件都包含 pingConfig 欄位。 使用這個欄位指定每次檢查要加入的 ICMP Ping 數量,最多為 3 個。根據預設,系統不會傳送任何 Ping。

      如要設定 Ping,請執行下列任一操作:

      • 使用 Google Cloud 控制台時,請展開「更多目標選項」,並在「ICMP Pings」欄位中輸入值。

      • 使用 Cloud Monitoring API 時,請使用 PingConfig 物件,結構如下:

        {
          "pingsCount": integer
        }
        

        如要進一步瞭解如何使用 Monitoring API 設定運作時間檢查,請參閱「建立運作時間檢查:API」或「編輯運作時間檢查:API」。

      驗證您的運作時間檢查

      在 Google Cloud 控制台中建立運作時間檢查時,您可以在儲存設定之前測試設定。

      檢查成功

      如果符合下列條件,運作時間檢查就會成功:

      • HTTP 狀態符合您選取的條件。
      • 回應沒有必要內容,或者在回應中搜尋必要內容成功。

      未通過檢查

      以下列舉一些運作時間檢查失敗的可能原因:

      • 連線錯誤 - 遭到拒絕:如果您使用預設的 HTTP 連線類型,請檢查您是否已安裝回應 HTTP 要求的網路伺服器。如果您尚未安裝網路伺服器,則可能會在新的執行個體上發生連線錯誤;請參閱 Compute Engine 快速入門導覽課程。如果您使用 HTTPS 連線類型,則可能必須執行其他設定步驟。如要解決防火牆問題,請參閱列出運作時間檢查伺服器 IP 位址
      • 找不到名稱或服務:主機名稱可能不正確。
      • 403 禁止:服務將錯誤代碼傳回至運作時間檢查工具。舉例來說,預設的 Apache 網路伺服器設定會在 Amazon Linux 之下傳回此代碼,但在其他某些 Linux 版本之下會傳回代碼 200 (成功)。請參閱 Amazon Linux 的 LAMP 教學課程或網路伺服器的說明文件。
      • 404 找不到:路徑可能不正確。
      • 408 要求逾時,或沒有回應:通訊埠編號可能不正確、服務可能並未執行、服務可能無法存取,或逾時可能太低。請檢查防火牆是否允許來自運作時間伺服器的流量;請參閱列出運作時間檢查伺服器 IP 位址。 逾時限制是 Response Validation (回應驗證) 選項的一部分。

        網路壅塞可能會導致要求逾時。舉例來說,由於網路暫時壅塞,您可能會發現一個檢查程式失敗,但所有其他檢查程式都成功。如果警報政策使用預設設定,單一檢查程式失敗不會觸發通知。

      如果運作時間檢查設定為傳送連線偵測 (ping),系統會將失敗的運作時間檢查連線偵測結果寫入 Cloud Logging。詳情請參閱「使用 ICMP Ping」。

      後續步驟