How to allow external traffic and deny inter pod communication using network policy?

11/5/2019

I am setting up my default namespace in my kubernetes cluster to allow incoming traffic from external nodes/hosts but deny any possible inter pod communication. I have 2 nginx pods which I want to completely isolate inside the cluster. Both pods are exposed with a service of the type nodePort and they are accessible from outside.

I first apply the following default deny network policy:

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

Then, I try allowing external traffic with the following network policy:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-external
spec:
  podSelector: {}
  ingress:
    - from:
        - ipBlock:
            cidr: 192.168.0.0/16

But unfortunately I am not able to access the service either from outside and inside my cluster.

Running example in: - macOS High Sierra v10.13.6 - minikube v1.5.2 --> with network plugin = cilium - kubectl v1.16.2

How could I face this problem?

-- Javier Errea
kubernetes
kubernetes-ingress
kubernetes-networkpolicy

1 Answer

11/5/2019

If you want to allow any incoming traffic to any pod except traffic that originates from your cluster you can use the "except" notation in a rule that allows traffic from all IP's. In below replace 172.17.1.0/24 with the cidr containing your pods:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all-internal
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  ingress:
  - from:
    - ipBlock:
        cidr: 0.0.0.0/0
        except:
        - 172.17.1.0/24
-- danielorn
Source: StackOverflow