在 Kubernetes 中,可以使用 NodeSelectorNodeAffinity 来指定 Service 只转发到当前 Node 上的 Pod。

  1. 使用 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。

  2. 使用 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 上

k8s 如何指定 service 只转发到当前node上面的pod

原文地址: https://www.cveoy.top/t/topic/hJ6a 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录