简体   繁体   中英

Network Policy in Kubernetes

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

The deny all policy should look like this:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
spec:
  podSelector: {}
  policyTypes:
  - Ingress

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM