Logo

Armand.nz

Home / About / Linkedin / Github

Create a Networkpolicy That Denies All Access to the a Pod or Namespace

#cka #ckd #kubernetes |

e.g. Create a Networkpolicy That Denies All Access to the Maintenance Pod

Here we add label to the namespace so that we can use the namespaceSelector (i was not able to get it working with name match, we need a label)

  1. Check the maintenance pod’s labels:
  kubectl describe pod maintenance -n foo
  1. Create a new YAML file named np-maintenance.yml:
  vim np-maintenance.yml

In the file, paste the following:

  apiVersion: networking.k8s.io/v1
  kind: NetworkPolicy
  metadata:
    name: np-maintenance
    namespace: foo
  spec:
    podSelector:
      matchLabels:
        app: maintenance
    policyTypes:
    - Ingress
    - Egress

Save the file

  1. Create the NetworkPolicy:
  kubectl create -f np-maintenance.yml

Create a Networkpolicy only Allows All Pods in a Namespace to Communicate

e.g. Create a Networkpolicy That Allows All Pods in the users-backend Namespace to Communicate with Each Other Only on a Specific Port

  1. Label the users-backend namespace:
  kubectl label namespace users-backend app=users-backend
  1. Create a YAML file named np-users-backend-80.yml:
  vim np-users-backend-80.yml

In the file, paste the following:

  apiVersion: networking.k8s.io/v1
  kind: NetworkPolicy
  metadata:
    name: np-users-backend-80
    namespace: users-backend
  spec:
    podSelector: {}
    policyTypes:
    - Ingress
    ingress:
    - from:
      - namespaceSelector:
          matchLabels:
            app: users-backend
      ports:
      - protocol: TCP
        port: 80

Save the file

  1. Create the NetworkPolicy:
  kubectl create -f np-users-backend-80.yml
comments powered byDisqus

Copyright © Armand