如何以编程方式引用Google Cloud上暴露的Kubernetes服务端点?
解决Kubernetes服务外部IP动态变化的问题
方案一:绑定静态外部IP(推荐长期使用)
在Google Cloud上创建静态外部IP并绑定到Kubernetes Service,就能固定每次部署后的访问地址,不用再手动查询。
操作步骤:
创建静态外部IP
gcloud compute addresses create my-static-ip --region=你的集群所在区域比如集群位于
us-central1区域,就替换成对应参数。查看并记录静态IP
gcloud compute addresses describe my-static-ip --region=你的集群所在区域复制输出里
address字段的IP值。绑定到Service
- 若用YAML文件部署Service,添加
loadBalancerIP字段指定静态IP:
应用配置:apiVersion: v1 kind: Service metadata: name: my-deployed-app-service spec: type: LoadBalancer loadBalancerIP: 你的静态IP地址 ports: - port: 80 targetPort: 5001 selector: app: 你的应用标签kubectl apply -f your-service.yaml - 若已有Service,直接编辑配置:
手动添加kubectl edit service my-deployed-app-serviceloadBalancerIP字段并填入静态IP即可。
- 若用YAML文件部署Service,添加
方案二:编程自动获取当前外部IP
如果不想用静态IP,可通过脚本自动拉取Service的外部IP,方便在Locust或其他自动化流程中调用。
Shell脚本示例:
# 循环等待IP分配完成,直到获取到有效IP APP_IP="" while [ -z "$APP_IP" ]; do APP_IP=$(kubectl get service my-deployed-app-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}') sleep 2 done echo "应用访问地址: http://$APP_IP:5001/"
Python脚本示例:
from kubernetes import client, config import time # 加载K8s配置(本地用~/.kube/config,集群内自动读取服务账号配置) config.load_kube_config() v1 = client.CoreV1Api() app_ip = None while not app_ip: try: service = v1.read_namespaced_service(name="my-deployed-app-service", namespace="default") if service.status.load_balancer and service.status.load_balancer.ingress: app_ip = service.status.load_balancer.ingress[0].ip except Exception as e: print(f"查询服务失败: {e}") time.sleep(2) print(f"应用访问地址: http://{app_ip}:5001/")
使用前需安装K8s Python客户端:pip install kubernetes
额外提示
- 静态IP在GCP会产生费用(未绑定资源时也收费),测试环境用编程获取的方式更灵活
- 若需要域名访问,可在GCP Cloud DNS中将域名解析到静态IP,直接通过域名调用应用
内容的提问来源于stack exchange,提问作者Robb1
相关产品推荐
相关产品推荐

