Introduction
In this new article we discuss about Network Policies.
What is a Network Policy ?
A network policy is a specification of how groups of pods are allowed to communicate with each other and other network endpoints.
NetworkPolicy resources use labels to select pods and define rules which specify what traffic is allowed to the selected pods.
How to create a Network Policy
Using a configuration YAML file
As usual, we create the following YAML File with the following mandatory parts :
apiVersion: kind: metadata: spec:
In our example, we want to apply our network policy to pods with the label “role=db” . It will be composed of the 2 main policy types (ingress and egress). The policyTypes field indicates whether or not the given policy applies to ingress traffic to selected pod, egress traffic from selected pods, or both.
The policy contains a single rule, which matches traffic on a single port, from one of three sources, the first specified via an ipBlock, the second via a namespaceSelector and the third via a podSelector.
The example policy will contain a single egress rule, which matches traffic on a single port to any destination in 10.0.0.0/24.
So let’s begin with these 4 sections :
- The api version in our case is “networking.k8s.io/v1”.
- The kind will be NetworkPolicy, for obvious reasons
- Metadata will contain the name of our network policy. It can obviously contain the namespace or labels.
- Finally, the “spec” is the most important part of our YAML file. It will contain information needed to define a particular network policy in the given namespace.
Here is our final YAML file called network-policy.yaml :
apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: test-network-policy namespace: default spec: podSelector: matchLabels: role: db policyTypes: - Ingress - Egress ingress: - from: - ipBlock: cidr: 172.17.0.0/16 except: - 172.17.1.0/24 - namespaceSelector: matchLabels: project: myproject - podSelector: matchLabels: role: frontend ports: - protocol: TCP port: 6379 egress: - to: - ipBlock: cidr: 10.0.0.0/24 ports: - protocol: TCP port: 5978
We can now deploy our network policy running the following command :
$ kubectl create -f network-policy.yaml
And that’s all !
Sources
kubernetes.io