使用內部 DNS 存取 VM


相同虛擬私有雲網路中的 VM 可以使用內部 DNS 名稱互相存取,不必使用 IP 位址。

事前準備

  • 如果尚未設定驗證,請先完成設定。 「驗證」是指驗證身分的程序,確認您有權存取 Google Cloud 服務和 API。如要從本機開發環境執行程式碼或範例,請選取下列其中一個選項,向 Compute Engine 進行驗證:

    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

      1. 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.

      2. Set a default region and zone.
      3. 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」。

判斷 VM 的內部 DNS 名稱

使用以下程序,讀取指派給 VM 執行個體的內部 DNS 名稱。您可以查詢 hostname 中繼資料項目,取得內部 DNS 名稱。

  1. 連線至 VM
  2. 查詢 hostname 中繼資料:

    Linux VM

    curl "http://metadata.google.internal/computeMetadata/v1/instance/hostname" \
      -H "Metadata-Flavor: Google"
    

    Windows VM

    Invoke-RestMethod `
      -Headers @{"Metadata-Flavor" = "Google"} `
      -Uri "http://metadata.google.internal/computeMetadata/v1/instance/hostname"
    

中繼資料伺服器會以下列其中一種格式傳回 VM 的主機名稱,顯示 VM 使用的內部 DNS 名稱類型:

  • 區域 DNSVM_NAME.ZONE.c.PROJECT_ID.internal
  • 全域 DNSVM_NAME.c.PROJECT_ID.internal

輸出內容:

  • VM_NAME:VM 名稱
  • ZONE:VM 所在的可用區
  • PROJECT_ID:VM 所屬的專案

透過內部 DNS 名稱存取 VM

如要存取 VM,請使用內部 DNS 名稱,而非 IP 位址。

以下範例使用 ping 聯絡使用區域 DNS 的 VM。如要使用這個方式,您必須先建立允許執行個體接收 ICMP 流量的防火牆規則

$ ping VM_NAME.ZONE.c.PROJECT_ID.internal -c 1

PING VM_NAME.ZONE.c.PROJECT_ID.internal (10.240.0.17) 56(84) bytes of data.
64 bytes from VM_NAME.ZONE.c.PROJECT_ID.internal (10.240.0.17): icmp_seq=1 ttl=64 time=0.136 ms

更改下列內容:

  • VM_NAME:VM 名稱
  • ZONE:VM 所在的可用區
  • PROJECT_ID:VM 所屬的專案

後續步驟