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

AKS中应用A同时通过内部Service DNS与外部FQDN访问应用B的方案

Kubernetes集群内外域名解析分流实现方案

需求背景

应用A与B运行在同一Kubernetes集群中,A当前通过环境变量B_HOST=b.example.com访问B。需要实现两种访问逻辑并存:

  • 集群内部(A的Pod内):执行curl b.example.com时,解析到B的Service DNS b.default.svc.cluster.local,通过集群内部Service访问B
  • 集群外部:执行curl b.example.com时,通过AGIC(Application Gateway Ingress Controller)管理的Ingress访问B

原方案HostAliases存在依赖固定Service IP、无法动态更新、无法修改已有Pod的问题,以下是更合理的实现方式:


方案一:集群级CoreDNS自定义解析(推荐)

利用Kubernetes默认的CoreDNS配置,在集群内部全局将b.example.com映射到B的Service DNS,无需修改应用配置。

操作步骤

  1. 编辑kube-system命名空间下的CoreDNS ConfigMap:
kubectl edit configmap coredns -n kube-system
  1. 在Corefile区块中添加自定义解析规则,示例如下:
data:
  Corefile: |
    .:53 {
        errors
        health {
           lameduck 5s
        }
        ready
        kubernetes cluster.local in-addr.arpa ip6.arpa {
           pods insecure
           fallthrough in-addr.arpa ip6.arpa
           ttl 30
        }
        # 添加自定义域名映射
        hosts {
          b.default.svc.cluster.local b.example.com
          fallthrough
        }
        prometheus :9153
        forward . /etc/resolv.conf {
           max_concurrent 1000
        }
        cache 30
        loop
        reload
        loadbalance
    }
  1. 保存退出后,CoreDNS Pod会自动重启加载新配置,此时集群内所有Pod访问b.example.com都会解析到B的Service,外部依然通过Ingress的DNS解析到Application Gateway。

方案二:Pod级DNS配置(仅针对应用A)

如果只需要让应用A的Pod实现该解析逻辑,可通过配置Pod的dnsConfig实现,不影响集群内其他应用。

操作步骤

  1. 修改应用A的Deployment YAML,添加dnsConfig字段:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-a
spec:
  replicas: 1
  selector:
    matchLabels:
      app: app-a
  template:
    metadata:
      labels:
        app: app-a
    spec:
      containers:
      - name: app-a
        image: your-app-a-image
        env:
        - name: B_HOST
          value: b.example.com
      # 自定义Pod DNS配置
      dnsConfig:
        hosts:
        - hostnames:
          - "b.example.com"
          ip: "b.default.svc.cluster.local"  # 直接使用Service DNS,CoreDNS会自动解析为实际IP
        options:
        - name: ndots
          value: "5"
  1. 重新部署应用A:
kubectl apply -f app-a-deployment.yaml

此配置仅对应用A的Pod生效,且无需关注Service IP的变化,CoreDNS会自动维护b.default.svc.cluster.local的解析。


方案三:修改应用环境变量(最直接)

如果应用A的代码逻辑允许,可直接将环境变量B_HOST的值改为b.default.svc.cluster.local,同时保留Ingress的b.example.com供外部访问。此方案无需修改集群DNS配置,但仅适用于允许调整B_HOST值的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 10:11:34