How can I isolate pods in namespace using NetworkPolicy without disabling external traffic to Kubernetes pods How can I isolate pods in namespace using NetworkPolicy without disabling external traffic to Kubernetes pods kubernetes kubernetes

How can I isolate pods in namespace using NetworkPolicy without disabling external traffic to Kubernetes pods


The NetworkPolicy you applied is blocking the traffic from every source.

You can add authorized CIDR blocks in your definition:

apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:  name: example-policy  namespace: defaultspec:  podSelector:    matchLabels:  policyTypes:  - Ingress  ingress:  - from:    - ipBlock:        cidr: 172.17.0.0/16


You can make sure that you namespace the NetworkPolicy resource and restrict the ingress/egress to just namespace.

apiVersion: extensions/v1beta1kind: NetworkPolicymetadata:  name: onlywithinnamespace  namespace: mynamespacespec:  ingress:  - from:    - namespaceSelector:        matchLabels:          role: mynamespace    - podSelector: {}  egress:  - to:    - namespaceSelector:        matchLabels:          role: mynamespace    - podSelector: {}  podSelector:    matchLabels:  policyTypes:  - Ingress  - Egress

Make sure that your namespace has the right labels to match:

apiVersion: v1kind: Namespacemetadata:  labels:    role: mynamespace  name: mynamespace


Using a kubernetes networkPolicy I don't believe its possible to deny communication between pods while allowing all external traffic. This is because the kubernetes networkPolicy resource doesn't have a concept of explicit Deny rules. I would either adjust your approach or consider another network policy that has Deny rules (such as Calico).

Solution:

apiVersion: projectcalico.org/v3kind: NetworkPolicymetadata:  name: deny-other-namespaces  namespace: prodspec:  selector: all()  types:  - Ingress  - Egress  ingress:  - action: Deny    protocol: TCP    source:      namespaceSelector: name == 'dev'  - action: Allow  egress:  - action: Allow