Home KubernetesKubernetes Network Policies: Isolate Pods Step by Step

Kubernetes Network Policies: Isolate Pods Step by Step

by Knowledge Base Linux
Kubernetes Network Policies isolate pods with firewall rules

Kubernetes Network Policies are the firewall rules of the cluster, and they exist because the Kubernetes default is wide open: any pod can talk to any other pod, in any namespace, on any port, unless something says otherwise. That flat network is convenient for development and dangerous in production, because a compromised frontend pod can reach a database pod directly, and a test namespace can reach production services by accident. A NetworkPolicy changes that default for the pods it selects, allowing only the traffic you explicitly permit and dropping the rest. This guide builds a practical set: a default-deny policy, an allow rule from frontend to backend, and an egress rule that keeps DNS working, then shows how to test and troubleshoot each one.

The first thing to understand is that a NetworkPolicy is only a declaration, not an enforcement engine. Something in the cluster must implement it, and that something is the Container Network Interface plugin. Calico, Cilium, and kube-ovn enforce NetworkPolicies; Flannel, the default in some distributions, does not. Applying a policy on a cluster whose CNI ignores it will look successful, because kubectl accepts the object, but no traffic will actually be blocked, which is worse than having no policy at all because it creates false confidence. Check your CNI before you rely on any policy in this guide. If you are still learning cluster networking, our guide to Kubernetes Ingress with NGINX covers the north-south traffic that NetworkPolicies complement, rather than replace.

Kubernetes Network Policies firewall gate between pod groups

Prerequisites

You need a Kubernetes cluster with kubectl configured, cluster-admin or namespace-admin permissions, and a CNI that enforces NetworkPolicies, such as Calico or Cilium. You should be comfortable creating pods and services and running kubectl exec for testing. The examples use a namespace called app with two deployments, frontend and backend, and a database service. Do not apply a default-deny policy to a production namespace as your first step: test in a dedicated namespace, prove the allow rules work, and only then roll the pattern out namespace by namespace.

Kubernetes Network Policies: Start with Default Deny

A default-deny policy selects every pod in a namespace and declares that no ingress and no egress is allowed unless another policy permits it. That sounds drastic, and it is, which is why it is the right starting point: with default deny in place, every new connection must be justified by an explicit rule, and forgotten traffic shows up as a clean failure instead of silent over-permission. Apply this policy to the test namespace first.

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

An empty podSelector selects all pods in the namespace, and listing both policy types means the policy governs both directions. Note what this policy does not do: it does not block traffic from pods to themselves, and it does not affect traffic that another policy explicitly allows. NetworkPolicies are additive, so a pod is governed by the union of every policy that selects it, and a connection is allowed if any selecting policy allows it. That additive behaviour is why default deny plus narrow allow rules is the safe pattern, while a single broad allow rule can undo the whole effort.

Apply the policy and confirm it exists before testing traffic, because a typo in the namespace field is the most common reason a policy appears to do nothing.

kubectl apply -f default-deny.yaml
kubectl -n app get networkpolicy
kubectl -n app describe networkpolicy default-deny

The official Kubernetes documentation on NetworkPolicies defines the full selector semantics, including namespaceSelector, podSelector, and ipBlock, and it is the reference for any rule beyond the examples here.

Kubernetes Network Policies: Allow Frontend to Backend and DNS

With default deny in place, the frontend cannot reach the backend, and no pod can resolve DNS, because DNS is egress traffic to the cluster DNS service. Fix both with two narrow policies. The first allows ingress to backend pods only from pods labelled app=frontend, and only on the backend port. The second allows egress from all pods in the namespace to the DNS service on port 53, for both UDP and TCP, because DNS uses UDP for most queries and falls back to TCP for large responses.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: backend-allow-frontend
  namespace: app
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 8080
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns
  namespace: app
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

Labels are the whole mechanism, so label discipline is a security control, not a naming preference. If any pod can be labelled app=frontend, then any pod can reach the backend, which is why production clusters combine NetworkPolicies with admission controls that restrict who can set sensitive labels. Test the rules with a temporary pod: run a busybox pod in the app namespace, try to reach the backend service, and try to reach an unrelated service. The first should succeed from a frontend-labelled pod and fail from an unlabelled one, and DNS resolution should work from every pod. For related workload isolation concepts, see our guide to Kubernetes affinity and anti-affinity scheduling, which controls where pods land rather than what they can reach.

kubectl -n app run test-pod --image=busybox --rm -it -- wget -qO- http://backend:8080
kubectl -n app run test-pod --image=busybox --rm -it -- nslookup kubernetes.default

Troubleshooting

When a policy seems to have no effect at all, check the CNI first. Run kubectl get pods in the kube-system namespace to identify the networking plugin, and confirm from its documentation that it enforces NetworkPolicies. On a managed cluster, the CNI is usually enforced, but on a kubeadm cluster with Flannel it is not, and no amount of policy editing will change that. Switching CNI on a running cluster is a significant change, so prove the problem in a test cluster before planning a migration.

When DNS breaks after default deny, the allow-dns policy is missing, wrong, or labelled incorrectly. The kube-dns label varies by distribution: some clusters use k8s-app=kube-dns, others use app.kubernetes.io/name=coredns. List the DNS pods and read their actual labels, then match the policy to reality instead of to a tutorial. When one specific connection fails, describe the policy and check which pods it selects, then test from a pod with the expected label and from one without it; if both fail, the policy is not selecting the destination, and if both succeed, the policy is not enforced. When a policy blocks traffic you did not intend to block, remember that policies are additive but never subtractive: another policy cannot re-block what one policy allows, so find the overly broad allow rule instead of adding a deny rule that will not work.

Conclusion

Kubernetes Network Policies reward a disciplined sequence: confirm the CNI enforces them, start with default deny in a test namespace, add one narrow allow rule at a time, and test each rule from both an allowed and a denied pod before moving on. DNS is the rule everyone forgets, labels are the mechanism everyone underestimates, and additive semantics are the surprise that breaks most first attempts. Get those three right, and pod isolation stops being a diagram and becomes a control you can demonstrate.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.