I have application running in K3s and want to implement network policy based on namespace only.
<br/><br/> Let's assume that currently I have three namespace A, B and C. I want to allow egress (external call to internet from pod) for namespace-A
and remaining namespace[B & C]
egress calls should be blocked/denied.<br/><br/> Is this possible in Kubernetes network policy (and not calico or cilium) ?
You can define a deny all egress
policy like described in the documentation:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-egress
namespce: your-namespace
spec:
podSelector: {}
policyTypes:
- Egress
This policy will be applied to all pods in the namespace because the pod selector is empty and that means (quoting documentation):
An empty podSelector selects all pods in the namespace.
The policy will block all egress traffic because it has Egress
as policy type but it doesn't have any egress
section.
If you want to allow in-cluster egress you might want to add an egress
section in the policy, like for example:
egress:
- to:
- namespaceSelector:
matchLabels:
networking/namespace: kube-system
podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- protocol: TCP
port: 53
- protocol: UDP
port: 53
This allows all traffic from the namespace where you create the network policy to pods labeled with k8s-app: kube-dns
in namespace kube-system
on port 53 (TCP and UDP).