kubernetes how to use network policy

In the kubernates environment to control Layer 3 or 4 traffic we can use network policy.

In this post I describe network policies with a simple examples

My lab setup

I have three nodes kubernetes cluster

There are a few pods running over there and pods have assigned label environments.I have three categories of pods are there.(dev, pods and web)

Im testing a few scenarios here

Scenario 01

Restrict both Ingress and egress traffic to\from web pods

This is the yaml file I used

—————————————

apiVersion: networking.k8s.io/v1

kind: NetworkPolicy

metadata:

  name: block-all-to-web

spec:

  podSelector:

    matchLabels:

environment: web

  policyTypes:

    – Ingress

    – Egress


How to create a network policy

Save the yml file and apply it

How to view network policy

how we can test this policy?

I have logged in to ubuntudev2 and trying to curl or ping to web pods. But we can connect to other pods

To test the egress traffic from web pods, I logged in to one of the web pods and tried to run apt update. But I’m getting a connection error.Which means our policy is working.

Scenario 02

In this scenario I have restricted only incoming traffic

To test this, i’m deleting the existing the policies now.

This is the yaml file I used.

——————————-

apiVersion: networking.k8s.io/v1

kind: NetworkPolicy

metadata:

  name: block-all-to-web

spec:

  podSelector:

    matchLabels:

      environment:  web

  policyTypes:

    – Ingress

After applying this policy , I was able to connect outside from web pods



Continue reading “kubernetes how to use network policy”