1

I am connecting Nodejs app with mongodb using kubernetes cluster. I want to ensure that mongo POD communicates only with Nodejs POD and deny any other POD traffic. When I apply the default deny policy and then apply the allow policy by app is not working.

I have come up with the following policies - why are they not working?

Default Deny Policy:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: default-deny
  namespace: default
spec:
  podSelector:
    matchLabels: {}

Network Policy:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: access-nodejs
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: nodejs-mongo
  ingress:
    - from:
      - podSelector:
          matchLabels:
            run: mongo
Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60
  • 2
    Did you forget to ask question? Also in your case it looks like you're allowing Mongo to connect to Nodejs while i suspect that it should be reverse, right? – Vasili Angapov Jan 24 '21 at 02:46
  • Yeah right, other then that change does my policy looks okay? I was thinking rather then `app: nodejs` Is there any way to specify network policy on pod, so that mongo POD can only communicate with nodejs POD? – user15068655 Jan 24 '21 at 02:55
  • @VasiliAngapov when I apply the default deny policy I am unable to access the app so that means my allow-access network policy is not working, can you help me on this? – user15068655 Jan 24 '21 at 05:30
  • Please post you whole manifests and also apply the change to your default deny policy from below answer. – Vasili Angapov Jan 24 '21 at 09:36

2 Answers2

1

I applied your policies and it worked for me. However, you don't have to specify deny-all policy. Once you create a Network Policy that allows pod to accept traffic from a specific set of pods it will be restricted by it. This way it will keep your setup simpler and will require less troubleshooting.

So in your case you can create a Network Policy that allows communication from a specific pod. Make sure you are using correct labels to select targeted pod(s) and pod(s) that it can accept traffic from.

Keep in mind that a NetworkPolicy is applied to a particular Namespace and only selects Pods in that particular Namespace.

Example policy that can be applied to accept traffic from pods matching it's selectors:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: backend-access
spec:
  podSelector:
    matchLabels:
      app: restricted-access #it selects pods that are targeted by this policy
  ingress:
    - from:
      - podSelector:
          matchLabels:
            app: allowed-traffic #selects pods that communicate with pods
kool
  • 3,214
  • 1
  • 10
  • 26
0

The deny all policy should look like this:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
spec:
  podSelector: {}
  policyTypes:
  - Ingress
Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60