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

如何在Kubernetes中使用含下划线的服务名web_api且不修改依赖服务?

解决Kubernetes中保留web_api访问地址的方案

问题本质

Kubernetes集群内部DNS遵循RFC 1123规范,域名标签不允许包含下划线,因此直接命名为web_api的Service无法通过集群DNS正常解析,导致http://web_api:10001访问失败。以下是无需修改依赖服务的可行方案:


方案1:CoreDNS自定义域名重写(推荐大规模场景)

修改集群CoreDNS的配置,将web_api域名重写为符合规范的Service名称(比如web-api):

  1. 先创建符合命名规范的目标Service:
apiVersion: v1
kind: Service
metadata:
  name: web-api
  namespace: my-system
spec:
  selector:
    app: web_api
  ports:
    - protocol: TCP
      port: 10001
      targetPort: 10001
  1. 编辑kube-system命名空间下的CoreDNS ConfigMap:
kubectl edit configmap coredns -n kube-system
  1. 在Corefile段添加rewrite规则:
rewrite name web_api.my-system.svc.cluster.local web-api.my-system.svc.cluster.local
  1. 重启CoreDNS Pod使配置生效:
kubectl rollout restart deployment coredns -n kube-system

此后所有对web_api:10001的请求都会被自动解析到web-api Service。


方案2:ExternalName类型别名Service

创建一个web_api名称的ExternalName Service,指向合规的web-api Service:

apiVersion: v1
kind: Service
metadata:
  name: web_api
  namespace: my-system
spec:
  type: ExternalName
  externalName: web-api.my-system.svc.cluster.local

集群DNS会将web_api解析为web-api的域名,实现访问地址兼容。若K8s对Service名称校验严格导致创建失败,优先使用方案1。


方案3:Pod hosts文件映射(适合小规模场景)

在依赖web_api的Pod部署配置中,添加hostAliases直接映射IP:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: 依赖服务名称
  namespace: my-system
spec:
  template:
    spec:
      hostAliases:
      - ip: "web-api Service的ClusterIP"
        hostnames:
        - "web_api"

此方式需逐个修改依赖服务的Deployment,仅适合服务数量较少的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:02:55