Today I Learned
Day 18 - NetworkPolicy Question
Question
There are existing Pods in Namespace space1 and space2 .
We need a new NetworkPolicy named np that restricts all Pods in Namespace space1 to only have outgoing traffic to Pods in Namespace space2 . Incoming traffic not affected.
We also need a new NetworkPolicy named np that restricts all Pods in Namespace space2 to only have incoming traffic from Pods in Namespace space1 . Outgoing traffic not affected.
The NetworkPolicies should still allow outgoing DNS traffic on port 53 TCP and UDP.Answer
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: np
namespace: space1
spec:
podSelector: {} # Select all pods
policyTypes:
- Egress
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: space2
- podSelector: {} # All pods
ports:
- protocol: TCP
port: 53
- protocol: UDP
port: 53
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: np
namespace: space2
spec:
podSelector: {} # Select all pods
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: space1
- podSelector: {} # All pods
ports:
- protocol: TCP
port: 53
- protocol: UDP
port: 53I just learned that if you want to test the connection using curl microservice1.space1.svc.cluster.local, you must allow outgoing port 53 for both UDP and TCP for space1. It's because when we call microservice1.space1.svc.cluster.local, it goes to kube-dns server through port 53 for DNS resolving.