NetworkPolicy

Prerequisites

# Launch the toolbox
ktbx desk

# Check your use kind-kind context
kubectx

#Launch initialization script
/home/k8s0/openshift-advanced/labs/3_policies/ex4-network.sh

# go to correct namespace
kubens network-k8s<ID>

Check that 3 pods have been created.

kubectl get pods --show-labels
NAME                 READY   STATUS    RESTARTS   AGE   LABELS
external             1/1     Running   0          2m   app=external
pgsql-postgresql-0   1/1     Running   0          2m   ...,tier=database
webserver            1/1     Running   0          2m   tier=webserver

Play with network policy

Look at the official documentation and at the examples

Prevent all ingress connections

Add a rule which prevents all ingress connections in the namespace

apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: default-deny spec: podSelector: {} policyTypes:

  • Ingress

Create network policy

Create a network policy to restrict ingress connection to pgsql-postgresql-0. Only webserver pod should be able to connect to pgsql-postgresql-0 on port 5432.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: ingress-www-db
spec:
  podSelector:
    matchLabels:
      tier: database
  ingress:
  - from:
    - podSelector:
        matchLabels:
          tier: webserver
    ports:
    - port: 5432
  policyTypes:
  - Ingress

Check network connections between pods

Using kubectl exec -n network-k8s0 external -- netcat -w 2 -zv pgsql-postgresql 5432

# webserver pod to database pod, using DNS name
kubectl exec -n network-k8s0 webserver -- netcat -q 2 -zv pgsql-postgresql 5432
pgsql-postgresql.network-k8s0.svc.cluster.local [10.96.205.70] 5432 (postgresql) open

# external pod to database pod
kubectl exec -n network-k8s0 external -- netcat -w 2 -zv pgsql-postgresql 5432
pgsql-postgresql.network-k8s0.svc.cluster.local [10.96.205.70] 5432 (postgresql) : Connection timed out

Reference

For more details, check the k8s-school NetworkPolicy lab.