01 — NetworkPolicy
MemorizeDefault deny, both directions
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: prod
spec:
podSelector: {} # empty = every pod in the namespace
policyTypes:
- Ingress
- Egress # omitting a type = that direction stays open
Allow DNS — required after any default-deny egress
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
ports:
- protocol: UDP
port: 53
- protocol: TCP
port: 53
Selector semantics
| Written as | Means |
|---|---|
- from: [{podSelector}, {namespaceSelector}] | OR — two separate sources |
- from: [{podSelector, namespaceSelector}] | AND — those pods in those namespaces |
podSelector: {} | all pods |
namespaceSelector: {} | all namespaces |
ipBlock.cidr + except | the only way to match non-pod IPs |
Verify
k get netpol -n prod k describe netpol default-deny -n prod k run t --image busybox --rm -it --restart Never -- wget -qO- -T 3 svc.ns:80
Gotchas
- Default-deny egress kills DNS. Symptom reads as "service is down", cause is name resolution.
- Policies are additive and allow-only — there is no deny rule and no ordering.
- A pod with zero matching policies is fully open; one matching policy locks it to that policy.
namespaceSelectormatches namespace labels.kubernetes.io/metadata.nameis set automatically on every namespace — use it.- The CNI must enforce policy. Flannel alone does not; k3s adds an enforcing controller by default.
Docs: kubernetes.io/docs/concepts/services-networking/network-policies/ — copy the "default deny all" examples at the bottom of the page.