Kubernetes 采用扁平网络模型,这意味着集群中的每个 Pod 默认情况下都能与其他 Pod 通信,无论它们位于哪个节点上。
下面的解释概述了 Kubernetes 的网络模型,演示了 Pod 如何使用分配的 IP 地址相互通信。
【代码清单】
# Example Deployment YAML
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello-world
spec:
replicas: 2
selector:
matchLabels:
app: hello-world
template:
metadata:
labels:
app: hello-world
spec:
containers:
- name: hello-container
image: k8s.gcr.io/echoserver:1.4
ports:
- containerPort: 8080
# Get the Pod IPs
kubectl get pods -o wide
# Curl one Pod from another using the Pod IP
kubectl exec -it <pod_name> -- curl <target_pod_ip>:8080
【执行结果】
kubectl exec 命令将从目标 Pod 中运行的 echoserver 返回 HTML 响应,这表明 Pod 可以使用它们的 IP 直接通信。
在 Kubernetes 中,每个 Pod 都会在群集的内部网络中被分配一个唯一的 IP 地址。这种扁平网络模型确保所有 Pod 无需 NAT(网络地址转换)即可相互通信。无论是使用云提供商的 CNI(容器网络接口)插件,还是内部部署的解决方案,Kubernetes 网络模型都对底层物理网络进行了抽象,确保了不同网络实现的一致性。
【小知识】
虽然扁平网络模型功能强大,但使用网络策略确保 Pod 之间的通信安全至关重要,尤其是在多租户环境中或处理敏感数据时。网络策略允许您限制 Pod 之间的流量,根据标签、命名空间和其他标准控制哪些 Pod 可以与其他 Pod 通信。