What is the difference between ingress and egress in a NetworkPolicy?
Quick Answer
In a NetworkPolicy, ingress rules control traffic coming into the selected pods; egress rules control traffic leaving them. A policy with neither is default-deny for whichever direction(s) it declares.
Detailed Answer
NetworkPolicy is directional. Ingress rules whitelist who may connect to the selected pods (by pod selector, namespace selector, or IP block, on specified ports). Egress rules whitelist where the selected pods may connect out to. The subtlety is the default: once a policy selects a pod and specifies a policyType, that direction becomes deny-by-default and only the listed rules are allowed; directions with no policy remain allowed. So a common pattern is a default-deny policy (selects all pods, empty ingress and egress) to lock everything down, then additive allow policies for the flows you want — e.g., allow egress to DNS (kube-dns on 53) and to the database namespace on 5432, deny the rest. Forgetting to allow DNS egress is a classic mistake that breaks name resolution cluster-wide.
Code Example
kind: NetworkPolicy
spec:
podSelector: {} # all pods in the namespace
policyTypes: [Ingress, Egress]
egress:
- to: [{ namespaceSelector: { matchLabels: { kubernetes.io/metadata.name: kube-system } } }]
ports: [{ protocol: UDP, port: 53 }] # don't forget DNS!
# (empty ingress => deny all inbound)Interview Tip
Call out the DNS gotcha: a default-deny egress policy that forgets to allow UDP 53 to kube-dns breaks name resolution for every selected pod. That detail proves you've actually shipped policies.