I have only one network policy in my cluster in prod namespace that allows only ingress rules. The network plugin is weave-net. No rules are configured for Egress so I am expecting egress traffic will be blocked. But until I restart the network daemon-set pods the rule has no effect. I know by best practices I should have default ingress and egress rules. But I want to understand the reason of this behavior. Is this step always required to restart the network-plugin pods?
1. Network Policy Definition
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: test-network-policy
namespace: prod
spec:
ingress:
- {}
podSelector:
matchLabels:
run: prod-nginx
policyTypes:
- Ingress
- Egress
2. Checking the netpol object
Name: test-network-policy
Namespace: prod
Created on: 2021-06-06 10:16:50 +0000 UTC
Labels: <none>
Annotations: <none>
Spec:
PodSelector: run=prod-nginx
Allowing ingress traffic:
To Port: <any> (traffic allowed to all ports)
From: <any> (traffic not restricted by source)
Allowing egress traffic:
<none> (Selected pods are isolated for egress connectivity)
Policy Types: Ingress, Egress
3. Testing egress traffic to nginx server (This is unexpected to my understanding)
Note: 10.39.0.5 is the IP of the nginx server running in 'test' namespace
Command : kubectl -n prod exec -it prod-nginx -- curl http://10.39.0.5 | grep successfully #egress
Response: <p>If you see this page, the nginx web server is successfully installed and
4. Restarted the weave-net pods
5. Retesting egress connection to same nginx server (expected)
Note: 10.39.0.5 is the IP of the nginx server running in 'test' namespace
Command: kubectl -n prod exec -it prod-nginx -- curl http://10.39.0.5 | grep successfully #egress**
Response: No connection
I would like to show you that restarting the
weave-net
Pods isn't required forNetworkPolicy
to take effect.Your
test-network-policy
NetworkPolicy
is applied to Pods with the labelrun=prod-nginx
in theprod
Namespace and allows all ingress traffic and denies all egress traffic.I will create an example to illustrate how it works.
First, I created the
prod-nginx
&prod-test
Pods and tested the connectivity with noNetworkPolicy
deployed:Everything works fine, so let's deploy a
test-network-policy
NetworkPolicy
and test again:We can see that the
prod-nginx
Pod can't connect to other Pods but can connect to itself:NOTE: A pod cannot block access to itself (see: Network Policies documentation)
Now let's create a
stage-nginx
Pod in thestage
namespace and check if theprod-nginx
Pod can connect to it:We have verified that the egress rule is working properly and restarting the
weave-net
Pods is not required.