在AKS中配置微服务通信 | AI生成和翻译

Home 2025.10

在 Azure Kubernetes 服务 (AKS) 中配置微服务间通信

在 Azure Kubernetes 服务 (AKS) 中,微服务通常作为由 Deployment 管理的 Pod 进行部署。为使它们能够相互通信(例如服务 A 调用服务 B),需要使用 Kubernetes Service 来抽象 Pod 的动态 IP 并提供稳定端点。这是通过内部网络利用 Kubernetes 内置的 DNS 解析实现的。以下是一步步的配置和实施指南。

1. 将微服务部署为 Deployments

每个微服务运行在一个 Pod(或一组用于扩展的 Pod)中。使用 Deployment 来管理它们。

简单微服务 Deployment 的 YAML 示例 (service-a-deployment.yaml):

   apiVersion: apps/v1
   kind: Deployment
   metadata:
     name: service-a
     namespace: default  # 或您的自定义命名空间
   spec:
     replicas: 3  # 按需扩展
     selector:
       matchLabels:
         app: service-a
     template:
       metadata:
         labels:
           app: service-a
       spec:
         containers:
         - name: service-a
           image: your-registry/service-a:latest  # 例如,ACR 或 Docker Hub 镜像
           ports:
           - containerPort: 8080  # 您的应用监听的端口

应用它:

   kubectl apply -f service-a-deployment.yaml

为其他服务(例如 service-b)重复此步骤。

2. 使用 Services 暴露微服务

为每个微服务创建一个 ClusterIP Service。此类型仅用于内部通信(不暴露到集群外部)。它对流量进行负载均衡到 Pod,并提供 DNS 名称。

服务 A 的 YAML 示例 (service-a-service.yaml):

   apiVersion: v1
   kind: Service
   metadata:
     name: service-a
     namespace: default
   spec:
     selector:
       app: service-a  # 匹配 Deployment 标签
     ports:
     - protocol: TCP
       port: 80  # Service 端口(调用者使用的端口)
       targetPort: 8080  # Pod 的容器端口
     type: ClusterIP  # 仅内部

应用它:

   kubectl apply -f service-a-service.yaml

对服务 B 执行相同操作。现在,Pod 可以通过 Service 的 DNS 名称相互访问。

3. 微服务如何相互调用

从 Pod 测试连通性:

   kubectl exec -it <pod-name-in-service-a> -- curl http://service-b:80/health

4. 高级配置选项

5. 最佳实践

此设置确保了可靠、可扩展的通信,而无需紧密耦合。从基本的 Services 开始,然后根据需要添加安全/网格层。

AKS 网络概述
Kubernetes Services 文档
AKS 微服务教程


Back

x-ai/grok-4-fast

Donate