Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
Vaardigheden in dit hoofdstuk
- NetworkPolicies en CNI-plugins
Know how policies work
Once any policy selects a pod for a direction, everything not allowed in that direction is blocked. Policies only allow; they add up.
| Part | Meaning |
|---|---|
podSelector | The pods this policy protects ({} = all in the namespace) |
policyTypes | Ingress, Egress or both |
from / to | Allowed peers: podSelector, namespaceSelector, ipBlock |
ports | Allowed ports and protocols |
Deny everything first
Start with "deny all" in a namespace, then allow what is needed.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: default-deny, namespace: shop }
spec:
podSelector: {}
policyTypes: [Ingress, Egress]Allow the needed traffic
Allow web → api on 8080, api → db on 5432, and DNS for everyone.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: api-from-web, namespace: shop }
spec:
podSelector: { matchLabels: { app: api } }
policyTypes: [Ingress]
ingress:
- from:
- podSelector: { matchLabels: { app: web } }
ports:
- { protocol: TCP, port: 8080 }
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: allow-dns, namespace: shop }
spec:
podSelector: {}
policyTypes: [Egress]
egress:
- to:
- namespaceSelector: { matchLabels: { kubernetes.io/metadata.name: kube-system } }
podSelector: { matchLabels: { k8s-app: kube-dns } }
ports:
- { protocol: UDP, port: 53 }
- { protocol: TCP, port: 53 }Let op
Inside one from item, namespaceSelector and podSelector together mean AND. Two separate - items mean OR. One dash more or less changes the meaning completely.
Allow traffic from other namespaces
Select namespaces by label; every namespace has kubernetes.io/metadata.name.
ingress:
- from:
- namespaceSelector:
matchLabels: { kubernetes.io/metadata.name: monitoring }
ports:
- { protocol: TCP, port: 9100 }Test the policies
Test from a pod with the right labels and from one without.
kubectl get networkpolicy -n shop
kubectl describe networkpolicy api-from-web -n shop
kubectl run t1 --rm -it -n shop --labels=app=web --image=busybox:1.36 --restart=Never -- wget -qO- -T 2 http://api:8080
kubectl run t2 --rm -it -n shop --labels=app=other --image=busybox:1.36 --restart=Never -- wget -qO- -T 2 http://api:8080
wget: download timed outExamentip
Read the task twice: which pods (selector), which direction (ingress or egress), from where (pods, namespaces, IPs) and which port.