我在阿里云上有一个 Kubernetes 集群,其中有一个 Next.js 托管服务,带有单个 pod,并且 Next.js 服务有一个服务器端 API 调用,可以从 AWS 中的 EC2 调用端点

因此,我需要在 AWS EC2 的安全组中添加传入规则,但是我的 Next.js 服务是什么 IP?
解决方案
解决方案是进入吊舱,发出 API 调用并捕获来源。
为此,我们可以执行以下操作:
# 获取 pod 列表并识别你的 pod 名称
kubectl -n <namespace> get pod
# 进入 pod 的 shell(使用 bash 或 sh,取决于你的容器)
kubectl -n <namespace> exec -it <your pod name> -- bash
# 从 shell 内部,curl 结果将包含来源
curl http://httpbin.org/ip
# 如果安装了 jq,则可以提取该字段:
# curl -s http://httpbin.org/ip | jq -r '.origin'
鉴于我的容器非常小并且没有安装 curl,而是安装了 node.js,所以我可以这样写:
const http = require ( 'http' );
function getOutgoingIPAddress ( ) {
return new Promise ( ( resolve, rejection ) => {
const options = {
hostname : 'httpbin.org' ,
path : '/ip' ,
method : 'GET'
};
const req = http.request ( options, ( res ) => {
let data = ' ' ;
res.on ( 'data' , ( chunk ) => {
data += chunk;
});
res.on ( 'end' , ( ) => {
const respond = JSON.parse (data); const
outgoingIPAddress = respond.origin ; resolve (outgoingIPAddress); }); }); req.on ( ' error ' , ( error ) => {
rejection (error); }); req.end ( ); }); } getOutgoingIPAddress () . then ( ( outgoingIPAddress ) => {
console.log ( '传出IP 地址:' , outgoingIPAddress); }) .catch ( ( error ) => {
console.error ( '错误:' , error ); } );
另一方面,如果您可以访问阿里云的管理控制台,则该信息位于 Kubernetes 集群的虚拟私有云 (VPC) 内部 NAT 网关的 EIP 中:
