kubernetesnamespaceskubernetes-podkubernetes-networkpolicy

Network policy to deny traffic from a particular namespace


So let's say I have 5 namespaces - prod, preprod, uat, dev, and test. Each namespace have a different label - ns=prod, ns=preprod, ns=uat, ns=dev, and ns=test.

Question: So I want to create a network policy where, I don't want to send traffic (egress) from ns=test to a particular namespace whose label is ns=prod. But ns=test should able to do egress to all other namespace.

Documentation: https://kubernetes.io/docs/concepts/services-networking/network-policies/ https://kubernetes.io/docs/tasks/administer-cluster/declare-network-policy/

I tried to create a manifest file from the above documentation but had no luck. I'm able to do this using podSelector (labels of pods, but not using only namespaces as a whole).


Solution

  • It would be easier if you could add the code snippet. However, it's not that tough to figure out what is going wrong.

    I am thinking something like this might be the issue with your network policy. Your pods might be requiring world wide web connection, so you cannot stop comms from test to prod through egress rule as you might be adding 0.0.0.0/0 to let your pods on any env to communicate to outer world to download external libraries or whatever stuff associated with your application.

    Due to this it is slightly difficult to add the egress rule to stop comms to any env. But on the contrary you can add igress rule to prod ns to not let communications from test or dev. Something like this might work, but again, we can change it based on needs.

    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: prod-network-policy
      namespace: prod
    spec:
      podSelector:
        matchLabels:
          ns: prod
      policyTypes:
      - Ingress
      - Egress
      ingress:
      - from:
        - namespaceSelector:
            matchLabels:
              ns: prod
              ns: dev
              ns: uat
        - podSelector:
            matchLabels:
              ns: prod
              ns: dev
              ns: uat
        - ipBlock:
            cidr: 10.0.1.101/32 #Assuming allow incoming request from ingress controller
      egress:
      - to: []
    

    There are several ways one can achieve this. But, I also sometimes refers to these example recipes on Github.

    Edit based on comment Addition of other namespaces to ingress rule to allow traffic from other namespaces except test.

    Hope this is helpful.