Does order of network policies matter in kubernetes?

I have a cluster on Google Kubernetes Engine, It has Network Policies enabled using Calico.
Until now I have written 12 Network Policies as a form of YAML files.
One thing I can't seem to figure out is that if the order in which these network policies are created matters.
For example lets say I have these two policies:
Pol#1- Deny all ingress connections

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

Pol#2- Allow db to be accessed by backend:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-db-to-be-accessed-by-backend
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: mysql
      release: production
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: backend
          release: production
    ports:
    - protocol: TCP
      port: 3306

Do I get different results if I apply Pol#1, then Pol#2 compared to applying Pol#2 first, and then Pol#1?


Solution 1:

No, it does not matter in which order you apply your rules. In your case Pol#2 rule will work anyway.

One more NetworkPolicy example: Suppose you have 2 policies: 1 rule to deny all traffic and 2nd one to allow traffic to chosen app. Whatever rule order you chose - ingress traffic will be allowed to pods with label app: web insight namespace: default

deny-all.yaml:

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

apply-nginx-app.yaml:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: web-allow-all
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: web
  ingress:
  - {}

Btw, you can find a lot of networkPolicies examples with a step-by step explanation here.

Hope it help.