Kubernetes interview question · Most asked
What are NetworkPolicies, and how would you lock down traffic in a namespace?
Summary
NetworkPolicies are firewall rules for pods: they select pods by label and allow specific ingress and egress traffic by pod selector, namespace selector, IP block and port. By default all pods can talk to all pods; once a policy selects a pod, only explicitly allowed traffic for that direction is permitted.
Longer Answer
A common baseline: a default-deny policy for ingress and egress in each namespace, then allow-list what each app needs (from the ingress controller to the web pods, from web to the API, from the API to the database, egress to DNS on port 53). Forgetting DNS egress is the usual first mistake.
Policies are enforced by the CNI plugin; with a CNI that does not support them, they are silently ignored. Plain NetworkPolicy works at L3/L4; for L7 rules or DNS-name-based egress, use CNI-specific policies (Cilium, Calico) or a service mesh.
Code Example
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: payments
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
Key Points
- Pod-level firewall rules by label.
- Default allow until a policy selects a pod.
- Default-deny, then allow-list; remember DNS.
- Needs a CNI that enforces them.
More most-asked Kubernetes questions
- Describe the Kubernetes architecture: what runs on the control plane and what runs on the nodes?
- How does the scheduler place pods? Explain resource requests, node affinity, taints and tolerations.
- Deployment, StatefulSet, DaemonSet, Job and CronJob: when do you use each?
- How do rolling updates work in a Deployment, and how do you roll back?
- Explain the Service types: ClusterIP, NodePort, LoadBalancer, ExternalName and headless.
- What happens, step by step, when you run kubectl apply for a Deployment?
- ConfigMaps and Secrets: how do they differ, and how should secrets really be handled?
- What is the difference between resource requests and limits, and what are the QoS classes?