Pod Affinity for a specific Namespace in Kubernetes

Viewed 3458

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?

2 Answers

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

The comment in the source code about the NamespaceSelector: https://github.com/kubernetes/kubernetes/blob/287888b191968198679159580b1bb76b529aa8c0/staging/src/k8s.io/api/core/v1/types.go#L2927

Example

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

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

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

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 .

Related