如何通过Azure VM公网IP暴露Kind Kubernetes集群中的Pod
如何通过Azure VM公网IP访问Kind集群中的Pod
问题描述
我有一台运行Ubuntu 22.04的Azure VM,在VM内部以Docker容器形式安装了Kind Kubernetes集群,并在k8s上部署了若干Pod。现在我希望通过VM的公网IP访问其中部分Pod。
我尝试了以下步骤:
- 按如下方式重新创建Kubernetes集群。我的Pod运行在8080端口,希望将其暴露到31190端口。
kind: Cluster apiVersion: kind.x-k8s.io/v1alpha4 nodes: - role: control-plane extraPortMappings: - containerPort: 8080 hostPort: 31190 protocol: TCP
- 为目标Pod的k8s清单文件指定Service类型为NodePort并分配端口
apiVersion: v1 kind: Service metadata: name: keycloak labels: app: keycloak spec: type: NodePort # Specifies the service type as NodePort selector: app: keycloak ports: - port: 8080 # The port on which the service is exposed internally targetPort: 8080 # The port on the container where the application is running nodePort: 31190 # The specific NodePort to expose the service externally
- 在Azure VM的NSG防火墙中允许以下流量:
- HTTP(TCP 80)
- TCP 31190端口
但我仍无法从外部访问Pod,例如通过http://<VM_Public_IP>:31190。如何正确配置?注:此操作仅用于学习,非生产项目。
修复步骤
1. 修正Kind集群的端口映射配置
当前extraPortMappings错误映射了Pod的端口到VM,实际需要映射的是Kind节点上的NodePort端口(31190)到VM的31190端口,同时要指定监听所有网卡:
修改Kind集群配置文件:
kind: Cluster apiVersion: kind.x-k8s.io/v1alpha4 nodes: - role: control-plane extraPortMappings: - containerPort: 31190 hostPort: 31190 protocol: TCP listenAddress: "0.0.0.0" # 确保端口绑定到VM的所有网卡,而非仅本地回环
删除旧集群并重新创建:
kind delete cluster kind create cluster --config=./your-cluster-config.yaml
2. 验证Service与Pod的关联
确认Service的selector能正确匹配Pod的标签:
- 执行命令查看Pod标签:
确认目标Pod存在kubectl get pods --show-labelsapp: keycloak标签 - 查看Service的端点状态:
检查kubectl describe service keycloakEndpoints字段,若显示Pod的IP和8080端口,说明关联正常;若为空,需修正selector或Pod标签
3. 开放Ubuntu本地防火墙
Ubuntu默认启用ufw,需允许31190端口的流量:
sudo ufw allow 31190/tcp sudo ufw reload
4. 检查端口监听状态
在Azure VM上执行以下命令,确认端口正常监听:
- 检查VM主机的端口监听:
sudo netstat -tulpn | grep 31190 - 检查Kind控制节点容器内的端口监听:
# 先获取Kind容器名称 docker ps | grep kind-control-plane # 进入容器检查端口 docker exec -it <kind-control-plane-container-name> netstat -tulpn | grep 31190
5. 分步测试连通性
- 在VM内部测试本地访问:
curl http://localhost:31190,确认服务正常响应 - 在VM内部测试通过私有IP访问:
curl http://<VM_Private_IP>:31190,确认跨网卡访问正常 - 从外部网络测试公网IP访问:
http://<VM_Public_IP>:31190
内容的提问来源于stack exchange,提问作者Minesh
相关产品推荐
相关产品推荐

