Create a NetworkPolicy that allows access to a pod from 2 specific pods

814 Views Asked by At

Assuming I have a pod that has a label app=foo in a namespace.

I only want this pod to be accessible from 2 other pods in the same namespace (and no other else pod being able to access it) via a NetworkPolicy

These pods have the following labels

pod1

labels:
  app: foo1
  type: frontend
labels:
  app: foo2
  type: backend

My question is whether I am able to define 2 podSelector fields in the ingress section of the NetworkPolicy as follows

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: my-network-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: foo
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: foo1
          type: frontend
    - podSelector:
        matchLabels:
          app: foo2
          type: backend
    ports:
    - protocol: TCP
      port: 6379

Is the above NetworkPolicy definition going to meet my requirements?

2

There are 2 best solutions below

0
On

yes I think so, I had to mention that manifest you wrote is applied only to that pod with label foo(restriction only to foo) and ingress traffic coming either from within the cluster or outside of it will be blocked ... however, both pods with label foo1 and foo2 can communicate or receive communication from anywhere inside your cluster . Have you implemented it ? what network plugin did you installed ?

0
On

Assuming that all these three pods are in the same namespace, yes, you have defined proper NetworkPolicy. Your yaml file is applied only to that pod with label foo - ingress traffic coming either from within the cluster or outside of it will be blocked but both pods with labels foo1 frontend and foo2 backend can communicate or receive communication from anywhere inside your cluster .

Note:

If you are declaring values or objects in default namespace you don't have put it in definition - like namespace: default. By default they will be assigned to it.

See: matching-expression-networkpolicy.

Read more: declaring-network-policy, network-policies.

Take a look: guide-network-policies.