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

WSL2下Kubernetes环境GET请求域名解析失败求助

问题原因分析

浏览器运行在Kubernetes集群外部(你的本地主机),无法接入集群内部的DNS服务,因此无法解析restapi-service这类集群内部服务域名。而登录请求正常是因为该请求由Web应用Pod(集群内部)发起,能正常通过集群DNS解析服务名;出现错误的GET请求是浏览器直接发起的,自然会遇到域名解析失败的问题。

解决方案

方案一:通过Web应用反向代理API请求

修改Web应用的配置,将前端的API请求转发到集群内部的REST API服务,利用Pod内部的DNS解析能力:

  • 如果是Vite构建的前端项目,在vite.config.js中添加代理规则:
    export default {
      server: {
        proxy: {
          '/api': {
            target: 'http://restapi-service:8080',
            changeOrigin: true,
            rewrite: path => path.replace(/^\/api/, '')
          }
        }
      }
    }
    
  • 前端代码中将API请求路径改为/api/Job/jobs?userId=3,请求会先发送到Web应用服务,再由Web应用转发到REST API服务。

方案二:将REST API服务暴露到外部

把restapi-service从ClusterIP类型改为NodePort,让外部能通过宿主机IP+端口访问:

  1. 修改服务类型:
    kubectl patch service restapi-service -p '{"spec":{"type":"NodePort"}}'
    
  2. 获取分配的NodePort端口:
    kubectl get service restapi-service
    
  3. 前端代码中使用http://localhost:<NodePort>/Job/jobs?userId=3作为请求地址,浏览器即可直接访问REST API。

方案三:使用Ingress统一管理外部访问

通过Ingress实现域名路由,适合多服务的外部访问管理(需先在Docker Desktop设置中启用Kubernetes Ingress控制器):

  1. 创建Ingress配置文件app-ingress.yaml:
    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      name: app-ingress
      annotations:
        nginx.ingress.kubernetes.io/rewrite-target: /$1
    spec:
      rules:
      - host: app.local
        http:
          paths:
          - path: /webui/(.*)
            pathType: Prefix
            backend:
              service:
                name: webui-service
                port:
                  number: 80
          - path: /api/(.*)
            pathType: Prefix
            backend:
              service:
                name: restapi-service
                port:
                  number: 8080
    
  2. 应用配置:
    kubectl apply -f app-ingress.yaml
    
  3. 在本地hosts文件(Windows为C:\Windows\System32\drivers\etc\hosts,WSL2为/etc/hosts)中添加:
    127.0.0.1 app.local
    
  4. 前端代码使用http://app.local/api/Job/jobs?userId=3访问API。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:07:17