如何查找 Google Cloud VM 的外部 IP?

在谷歌云平台(GCP)服务器上查找外部 IP 地址

您是否正在进行一个项目,需要获取应用程序的虚拟机实例的外部(互联网/公共)IP 地址?

好消息是,您可以快速地找到它们。

您可能已经尝试过运行 ifconfig 命令,但您会发现结果中只包含内部 IP 地址。

GCP 和 AWS 都提供了方便的 Web 界面,您可以在其中查看公共 IP,但如果您需要在服务器上直接获取它们,下面的命令将非常有用。

在 GCP 虚拟机上获取外部 IP 的方法

我知道有两种常用的方法。 第一种是使用 gcloud 命令。

gcloud compute addresses list

上述命令会显示您项目的所有 IP 地址。 这对于当您登录到虚拟机时进行故障排除或快速查看很有帮助。

例如:

[email protected]:~# gcloud compute addresses list
NAME                  ADDRESS/RANGE   TYPE      PURPOSE       NETWORK  REGION    SUBNET   STATUS
instance-1           xx.xx.xx.xx                                   us-west1           IN_USE
techblik.com-nexus  xx.xx.xx.xx      INTERNAL  GCE_ENDPOINT           us-west1  default  IN_USE
techblik.com               xx.xx.xx.xx                                     us-west1           IN_USE
techblik.com-tools          xx.xx.xx.xx                                   us-west1           IN_USE
[email protected]:~#

第二种方法是使用 curl 命令来访问元数据服务。

curl -H "Metadata-Flavor: Google" http://metadata/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip

请注意:如果您有多个网络接口,您需要将 network-interfaces 后的 0 相应地更改为 12

元数据功能非常强大,您可以使用它检索大量的指标。

[email protected]:~# curl -H "Metadata-Flavor: Google" http://metadata/computeMetadata/v1/instance/
attributes/
cpu-platform
description
disks/
guest-attributes/
hostname
id
image
licenses/
machine-type
maintenance-event
name
network-interfaces/
preempted
remaining-cpu-time
scheduling/
service-accounts/
tags
virtual-clock/
zone
[email protected]:~#

您可以看到,它返回了许多有用的信息。

这对于报告和自动化任务来说非常方便。

如果您还需要获取内部 IP 地址,请使用以下命令:

curl -H "Metadata-Flavor: Google" http://metadata/computeMetadata/v1/instance/network-interfaces/0/ip

您正在学习 GCP 管理吗? 可以看看这个超棒的 在线课程

喜欢这篇文章吗? 把它分享出去吧!