NetworkPolicy Kubernetes
This time i will create a deployment which will have an nginx as an image and i will run two alpine pods and use their shell to access the website (one pods won’t be able to curl the page since we will use a network policy to deny it)
For clarification:
The entities that a Pod can communicate with are identified through a combination of the following 3 identifiers:
Other pods that are allowed (exception: a pod cannot block access to itself)
Namespaces that are allowed
IP blocks (exception: traffic to and from the node where a Pod is running is always allowed, regardless of the IP address of the Pod or the node)
When defining a pod- or namespace- based NetworkPolicy, you use a selector to specify what traffic is allowed to and from the Pod(s) that match the selector.
Meanwhile, when IP based NetworkPolicies are created, we define policies based on IP blocks (CIDR ranges).
Deployment.yml file content
Now i will define my network policy :
Run two alpine pods
kubectl run curlpod --image=alpine -- /bin/sh -c "sleep 3600”
Add the label (Necessary for the network policy):
Since i will allow only pods with ‘app=curlpod’ label to hit the webpage i will add it to the first pod
kubectl label pods curlpod app=curlpod
Second pod:
kubectl run curlpod2 --image=alpine -- /bin/sh -c "sleep 3600”
Add the label for this pod:
kubectl label pods curlpod2 app=myapp2
Now this pod wont be able to access the web page since it’s label is not listed in the netwrok policy ‘matchLabels’ section
kubectl exec -it curlpod -- /bin/sh
kubectl exec -it curlpod2 -- /bin/sh