Here is the sample NetworkPolicy which allows connection to pods that have a label hello
and allow port connection on 53 TCP and UDP and block all ports.
How I can make this to allow all ports and block 53 TCP and UDP (egress).
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: foo-allow-to-hello
spec:
policyTypes:
- Egress
podSelector:
matchLabels:
app: foo
egress:
- to:
- podSelector:
matchLabels:
app: hello
- ports:
- port: 53
protocol: TCP
- port: 53
protocol: UDP
Unfortunately, Kubernetes native NetworkPolicies don't have a 'deny' feature, so this will be very painful if you were to list every port that you want to allow except port 53
. Currently, there is an open feature request to allow port ranges in K8s network policies which would allow much more simplification.
With that said, there are other alternatives. If you are using an overlay like Calico, you have access to a richer NetworkPolicy
with actions. For example:
apiVersion: projectcalico.org/v3
kind: NetworkPolicy
metadata:
name: deny-dns
namespace: mynamespace
spec:
selector: app == 'hello'
types:
- Ingress
- Egress
egress:
- action: Deny
metadata:
annotations:
from: helloworld
to: dns
protocol: TCP
source:
selector: app == 'hello'
destination:
ports:
- 53
- action: Deny
metadata:
annotations:
from: helloworld
to: dns
protocol: UDP
source:
selector: app == 'hello'
destination:
ports:
- 53
ingress:
- action: Allow
You can also find some other workarounds like applying an ingress policy to your coredns pods that allow certain pods/namespaces.