Understanding Network Policies — Kubernetes

Joan Ngugi
3 min readMar 12, 2020

Traffic lights are used to control the movement of traffic. They facilitate the movement and direction of traffic for safety and avoidance of collision. Likewise in Kubernetes, network policies are used to control the traffic requests from and into our Pods.

By default, pods can accept traffic from any source. We would however not want any traffic sending requests to our pods. Hence the need for a Network policy.

What is a Network Policy

Network policies simply are rules that control traffic from and to the Pod. A rule can be for instance allowing Pod A to Communicate to B but B cannot communicate to A.

How to Create a Network Policy

Network Policy is created with the help of label selectors. The NetworkPolicy applies to pods that match its label selector.

When creating a Network Policy there is the question of who and which.

  • Which direction is the traffic coming from and which traffic is the traffic going to. (Ingress and Egress)

Ingress is an English word that means the action of going in.

Egress is an English word that means the action of going out or leaving a place.

  • Who is allowed

NetworkPolicy Definition

apiVersion: networking.K8s.io/v1
kind: NetworkPolicy
metadata:
name: demo-network-policy
namespace: mynamespace
spec:
podSelector:
matchLabels:
app: database #policy applies to pods with app:database label
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: webserver #allows incoming connection from pods with app: webserver label
ports:
- port: 3306
egress:
-to:
...
  • By default pods in a given namespace can be accessed by anyone. When you create a NetworkPolicy in a certain namespace no one can connect to any pod in that namespace unless their labels match with the one specified in the NetworkPolicy. For instance, in a namespace with many pods, you would want only one pod to connect to your database. You would, therefore, create a NetworkPolicy that applies to labels matching the database labels.

Example

  1. Create a namespace called testpolicy.

2. Create a backend, frontend and database pod in the created namespace. The pods should run on image nginx and should have labels. Frontend pod should have label app:myapp and tier: frontend. Backend pod should have label app: myapp and tier: backend. Database should have label app: myapp and tier: database.

3. Create a network policy that allows Incoming traffic from the backend to the database. Incoming traffic to the database should be allowed on TCP port 3306 and no other port.

4. Create the network policy by creating it in the testpolicy namespace.

5. View your network policy.

Out network policy created above will be applied to any pod matching label app:myapp and tier:database which in our case is the database pod.

--

--