I was tempting to try out NetworkPolicy
on Kubernetes as a secure way to protect traffic in and out the namespaces but never managed to actuall do it.
Today a friend of mine who was pursuing “Certified Kubernetes Application Developer” asked me a problem related to it. He was using a small set of exercises to practice Kubernetes. The problem statement was:
Create an nginx deployment of 2 replicas, expose it via a ClusterIP service on port 80. Create a NetworkPolicy so that only pods with labels ‘access: granted’ can access the deployment and apply it
The guide also included the solution and he tried it on his test environment and it didn’t work. The deployed network policy did not take effect at all.
At first, I thought it might be because he did not deploy a “deny-all” policy as described in the page. This practice seemed like a good practice that almost all serious production-ready solution used (e.g CouchBase Operator).
|
|
But my friend tried that and it still DIDN’T work. Hmm! So I thought “Interesting! Let’s try!”.
I was using a MacBook Pro and installed Docker for macOS. I didn’t want to use any managed Kubernetes cluster available online because I didn’t want to waste time on them. I chose to use Kind as it allowed to set up a Kubernetes cluster on the existing Docker Engine.
kind is a tool for running local Kubernetes clusters using Docker container “nodes”.
kind was primarily designed for testing Kubernetes itself, but may be used for local development or CI.
|
|
Once I had a Kubernetes cluster running, I ran the same set of commands suggested by the exercise and, interestingly, reproduced the issue.
I decided to read the Kubernetes’ NetworkPolicy
page 1 very carefully again. The “Aha!” moment came:
Make sure you’ve configured a network provider with network policy support. There are a number of network providers that support NetworkPolicy, including:
Okay! So NetworkPolicy
did not come out-of-the-box in a Kubernetes cluster. And to top it off, the exercise DID NOTICE THAT as well:
[..] Note that network policies may not be enforced by default, depending on your k8s implementation. E.g. Azure AKS by default won’t have policy enforcement, the cluster must be created with an explicit support for
netpol
https://docs.microsoft.com/en-us/azure/aks/use-network-policies#overview-of-network-policy [..]
Shame on me!
In order to test the NetworkPolicy
, I had to see if the cluster created by Kind supported network policy? Turned out that it was supported…eventually.
According to the GitHub issue "#842 NetworkPolicy support" (which was still open as of this writing), Kind could provide support for network policies by installing Calico. The most voted comment (thankfully!) showed how to do it.
To sum it up:
|
|
NetworkPolicy
is not out-of-the-box. Check the network provider installed for Kubernetes cluster.