Deny and allow traffic between pods in Kubernetes

6/29/2021

I have a deployment with several Namespaces and in this namespaces I have several pods, i.e:

NS1:

  • Pod1 -> Label: (app= Pod1)
  • Pod2 -> Label: (app= Pod2)
  • PodDB-> Label: (app= PodDB)

NS2:

  • Pod1 -> Label: (app= Pod1)
  • Pod2 -> Label: (app= Pod2)
  • PodDB -> Label: (app= PodDB)

I would like to restrict access between them in a way that Pod1 only can access to PodDB but not with Pod2..I would like also restrict traffic between different namespaces. I'm reading the docs but I dont understand how to do it. I tried several NetworkPolicies but with no success because I don't know how to apply specific deny/access to a specific pod.

Any help?

Thanks a lot.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: test-network-policy
  namespace: uk
spec:
  podSelector:
    matchLabels:
      app: Pod1
  policyTypes:
    - Ingress
  ingress:
    - from:
      - podSelector:
          matchLabels:
            app: Pod2
-- Humberto Lantero
amazon-eks
kubernetes

1 Answer

6/29/2021

You can use this editor to help you create your NetworkPolicies: https://editor.cilium.io/

Editor network policy

The following manifest will be applied to pod with label app=Pod1 and will disable all incoming/outgoing call to/from such pods, except outgoing calls to pods with labels app=PodDB. (See screenshot below with the colors that helped a lot to understand).

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: pod1-policy
  namespace: NS1
spec:
  # the following selector specifies to which pods the rules will be applied
  podSelector:
    matchLabels:
      app: Pod1
  policyTypes:
    - Ingress
    - Egress
  # the following rule deny all incoming requests
  ingress: []
  # the following rule authorize outgoing call only to pod with label app=podDB
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: PodDB
-- Arnaud Develay
Source: StackOverflow