You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将IP地址映射到Localhost,从主机外部访问Kubernetes Pod?

解决Kubernetes NodePort服务无法通过虚拟机IP访问的问题

问题背景

我在Ubuntu虚拟机中使用Docker Desktop集成的Kubernetes环境,部署了以下Deployment和Service资源:

Deployment.yaml

kind: Deployment
metadata:
  labels:
    app: rhap
  name: deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: rhap
  template:
    metadata:
      labels:
        app: rhap
    spec:
      containers:
      - image: image:release1
        name: rhap

Service.yaml

apiVersion: v1
kind: Service
metadata:
  name: rhap-service

spec:
  selector:
    app: rhap

  ports:
    - name: cport
      port: 8444
      nodePort: 30080
    - name: iport
      port: 3041
      nodePort: 30081
    - name: bport
      port: 4031
      nodePort: 30082
    - name: uport
      port: 31002
      nodePort: 31002

  type: NodePort

当前状态:

  • 可在Ubuntu虚拟机内通过https://localhost:30080访问应用
  • 虚拟机内部及外部的本地笔记本,均无法通过https://<虚拟机IP>:30080访问应用
  • 可正常ping通虚拟机IP

解决步骤

1. 调整Docker Desktop Kubernetes端口监听范围

Docker Desktop在Linux上运行Kubernetes时,默认可能仅绑定127.0.0.1,导致外部无法通过虚拟机IP访问:

  • 打开Docker Desktop设置 → Kubernetes选项卡
  • 找到端口绑定配置,设置NodePort服务监听0.0.0.0(所有IP)
  • 重启Docker Desktop和Kubernetes服务

2. 配置Ubuntu防火墙规则

Ubuntu默认的ufw防火墙可能拦截了NodePort端口:

  • 临时关闭防火墙测试:
    sudo ufw disable
    
    测试如果能访问,说明是防火墙问题,添加允许规则:
    sudo ufw allow 30080/tcp
    sudo ufw allow 30081/tcp
    sudo ufw allow 30082/tcp
    sudo ufw allow 31002/tcp
    sudo ufw reload
    

3. 验证Service及端口监听状态

确认Service配置和端口监听正常:

  • 查看Service详情:
    kubectl describe service rhap-service
    
    确认NodePort字段与配置一致
  • 检查端口监听情况:
    netstat -tulpn | grep 30080
    
    确保端口被kube-proxy监听,且监听地址为0.0.0.0

4. 配置iptables端口转发

如果Docker Desktop Kubernetes仅监听localhost,可通过iptables转发虚拟机IP的请求:

  • 添加转发规则:
    sudo iptables -t nat -A PREROUTING -p tcp --dport 30080 -j DNAT --to-destination 127.0.0.1:30080
    sudo iptables -t nat -A POSTROUTING -p tcp --dport 30080 -d 127.0.0.1 -j SNAT --to-source <你的虚拟机IP>
    
  • 保存规则:
    sudo iptables-save | sudo tee /etc/iptables/rules.v4
    

5. 检查虚拟机网络模式

确保虚拟机网络允许外部访问:

  • 将虚拟机的网络适配器设置为桥接模式,使其获取局域网内独立IP(避免NAT模式需要额外端口转发)
  • 确认Docker Desktop使用桥接网络模式,在Docker设置 → Network选项卡中配置

内容的提问来源于stack exchange,提问作者Aravind Raghunath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 11:18:17