k8s 如何指定 service 只转发到当前node上面的pod
在 Kubernetes 中,可以使用 NodeSelector 和 NodeAffinity 来指定 Service 只转发到当前 Node 上的 Pod。
-
使用
NodeSelector:- 创建一个带有
nodeSelector字段的 Service,该字段指定了 Pod 必须在具有特定标签的 Node 上运行。 - 在 Pod 的定义中,为 Pod 添加与 Service 中指定的标签相匹配的标签。
示例 Service 定义:
apiVersion: v1 kind: Service metadata: name: my-service spec: selector: app: my-app ports: - protocol: TCP port: 80 targetPort: 8080 type: ClusterIP externalTrafficPolicy: Local nodeSelector: my-label-key: my-label-value示例 Pod 定义:
apiVersion: v1 kind: Pod metadata: name: my-pod labels: app: my-app my-label-key: my-label-value spec: containers: - name: my-container image: nginx通过以上配置,Service 将只会将流量转发到带有
my-label-key=my-label-value标签的 Node 上的 Pod。 - 创建一个带有
-
使用
NodeAffinity:- 创建一个带有
nodeAffinity字段的 Service,该字段使用 Node 亲和性规则来指定 Pod 必须在满足指定条件的 Node 上运行。 - 在 Pod 的定义中,为 Pod 添加与 Service 中指定的亲和性规则相匹配的规则。
示例 Service 定义:
apiVersion: v1 kind: Service metadata: name: my-service spec: selector: app: my-app ports: - protocol: TCP port: 80 targetPort: 8080 type: ClusterIP externalTrafficPolicy: Local nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: my-label-key operator: In values: - my-label-value示例 Pod 定义:
apiVersion: v1 kind: Pod metadata: name: my-pod labels: app: my-app spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: my-label-key operator: In values: - my-label-value containers: - name: my-container image: nginx通过以上配置,Service 将只会将流量转发到满足
my-label-key=my-label-value的 Pod 所在的 Node 上 - 创建一个带有
原文地址: https://www.cveoy.top/t/topic/hJ6a 著作权归作者所有。请勿转载和采集!