Pod Affinity for a specific Namespace in Kubernetes

7/9/2020

I would like to deploy my pods in a specific namespace. I think about Pod Affinity but can't find a solution on how to select specific namespace. Does anybody do it?

-- debek
google-kubernetes-engine
kubernetes

2 Answers

3/22/2021

As part of Anti-Affinity you can provide namespaces: [] to allow the labelSelector to match labels on pods from all namespaces instead of the pod's own namespace only.

Kubernetes Affinity/Anti-Affinity Design https://github.com/kubernetes/community/blob/master/contributors/design-proposals/scheduling/podaffinity.md

Example

          affinity:
            podAntiAffinity:
              preferredDuringSchedulingIgnoredDuringExecution:
                - weight: 100
                  podAffinityTerm:
                    labelSelector:
                      matchExpressions:
                        - key: app.kubernetes.io/name
                          operator: In
                          values:
                            - foobar
                    topologyKey: "kubernetes.io/hostname"
                    namespaces: []

EDIT: The namespaceSelctor for pod affinity is in Alpha v1.21

Feature disscusion: https://github.com/kubernetes/kubernetes/issues/68827

-- levich
Source: StackOverflow

7/9/2020

Pod anti-affinity is about telling Kubernetes to schedule (run) this pod X in a node (machine) far away than nodes running other pods Y.

So :

  • What's X ?
  • What's Y ?
  • What's the criterion of "far away" ?

See this example:

apiVersion: v1
kind: Pod
metadata:
  name: pod-x
spec:
  affinity:
    podAntiAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          labelSelector:
            matchExpressions:
            - key: y-key
              operator: In
              values:
              - y-value
          topologyKey: failure-domain.beta.kubernetes.io/zone

In this example :

  • X is pod-x
  • Y is any pod has label (y-key=y-value)
  • "Far away" criteria is failure-domain.beta.kubernetes.io/zone

If this is clear, you will see that namespaces are nothing to do with anti-affinity or even affinity.

looking into official doc is a good practice also .

-- Abdennour TOUMI
Source: StackOverflow