同一虚拟私有云网络中的虚拟机可以使用内部 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
-
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.
- Set a default region and zone.
- 连接到虚拟机。
查询
hostname
元数据:Linux 虚拟机
curl "http://metadata.google.internal/computeMetadata/v1/instance/hostname" \ -H "Metadata-Flavor: Google"
Windows 虚拟机
Invoke-RestMethod ` -Headers @{"Metadata-Flavor" = "Google"} ` -Uri "http://metadata.google.internal/computeMetadata/v1/instance/hostname"
- 区域 DNS:
VM_NAME
.ZONE
.c
.PROJECT_ID
.internal
- 全球 DNS:
VM_NAME
.c
.PROJECT_ID
.internal
VM_NAME
:虚拟机的名称ZONE
:该虚拟机所在的可用区PROJECT_ID
:虚拟机所属的项目VM_NAME
:虚拟机的名称ZONE
:该虚拟机所在的可用区PROJECT_ID
:虚拟机所属的项目- 迁移至区域 DNS
- 详细了解 Compute Engine 的内部 DNS 名称。
- 为虚拟机创建静态 IP 地址。
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 身份验证文档中的使用 REST 时进行身份验证。
确定虚拟机的内部 DNS 名称
按照以下过程读取分配给虚拟机实例的内部 DNS 名称。您可以通过查询
hostname
元数据条目来获取内部 DNS 名称。元数据服务器以以下某一格式返回虚拟机的主机名,并且显示虚拟机使用的内部 DNS 名称的类型:
在输出中:
按内部 DNS 名称访问虚拟机
若要访问虚拟机,请使用内部 DNS 名称代替 IP 地址。
以下示例使用
ping
来与使用区域 DNS的虚拟机进行同学呢。如果您已创建允许传入 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
替换以下内容:
后续步骤
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-06-25。
-