kubernetes

Kubernetes NetworkPolicy Explained: Control Pod-to-Pod Communication

Learn Kubernetes NetworkPolicy with practical ingress, egress, selectors, default-deny policies, DNS considerations, troubleshooting, and production best practices.

By Shubhankar Tripathi • • 5 min read

Kubernetes NetworkPolicy Explained: Controlling Pod-to-Pod Communication

Kubernetes makes Pod networking intentionally open by default: Pods can generally communicate with other Pods across the cluster. That model is convenient for application connectivity, but it is not sufficient for every production environment. A compromised frontend Pod, for example, should not automatically be able to connect to every database, cache, or internal service.

Kubernetes NetworkPolicy provides an application-centric way to control network traffic to and from selected Pods at the IP address and port level. This article explains how NetworkPolicy works, how ingress and egress rules are evaluated, how selectors behave, how to design default-deny policies, and how to troubleshoot common connectivity problems.

1. What Is Kubernetes NetworkPolicy?

NetworkPolicy is a Kubernetes API resource used to specify which network connections are allowed for a selected set of Pods. Policies can control ingress traffic to Pods and egress traffic from Pods. NetworkPolicy operates at OSI Layer 3/4 concepts such as IP addresses, ports, and protocols.

A critical requirement is that the cluster's networking implementation must support NetworkPolicy enforcement. Creating a NetworkPolicy object in the Kubernetes API does not by itself enforce traffic filtering.

Concept

Meaning

NetworkPolicy

Kubernetes API object describing allowed network traffic.

podSelector

Selects the Pods to which the policy applies.

Ingress

Controls incoming connections to selected Pods.

Egress

Controls outgoing connections from selected Pods.

namespaceSelector

Selects namespaces by labels.

ipBlock

Selects IP ranges using CIDR notation.

ports

Restricts allowed traffic to specified ports/protocols.

CNI/network plugin

The networking implementation that must enforce the policy.

2. Why NetworkPolicy Matters

  • Reduce unnecessary Pod-to-Pod communication.

  • Create network segmentation between application tiers.

  • Limit which workloads can reach databases, caches, or internal APIs.

  • Restrict outbound traffic from sensitive workloads.

  • Provide a network-level defense-in-depth control if a workload is compromised.

NetworkPolicy should be treated as one layer of security, not as a replacement for application authentication, authorization, encryption, secrets management, or host security.

3. Kubernetes Networking Before NetworkPolicy

Kubernetes networking gives each Pod its own cluster-wide IP address. In the standard Kubernetes networking model, Pods can communicate with other Pods without requiring port mappings between containers. NetworkPolicy adds traffic restrictions on top of that connectivity model.

A useful mental model is: Kubernetes provides the connectivity model, Services provide stable discovery and access to workloads, and NetworkPolicy determines which connections involving selected Pods are permitted.

4. NetworkPolicy Resource Structure

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-api
  namespace: app
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080

The podSelector identifies the destination Pods in this example. The policy then allows TCP traffic on port 8080 from Pods labeled app=frontend in the same namespace.

5. Understanding podSelector

Every NetworkPolicy has a podSelector. It determines which Pods are selected by that policy. An empty podSelector selects all Pods in the policy's namespace.

spec:
  podSelector:
    matchLabels:
      app: database

The policy above applies to Pods labeled app=database. It does not automatically apply to Pods in other namespaces.

Empty podSelector

spec:
  podSelector: {}

An empty selector means all Pods in that namespace are selected. This is especially useful for namespace-wide default-deny policies.

6. Ingress: Controlling Incoming Traffic

Ingress rules control traffic coming into selected Pods. For example, a database workload might allow connections only from the application tier.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-api-to-db
spec:
  podSelector:
    matchLabels:
      app: db
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: api
    ports:
    - protocol: TCP
      port: 5432

This policy selects database Pods and allows TCP connections on port 5432 from Pods labeled app=api in the same namespace.

7. Egress: Controlling Outgoing Traffic

Egress rules control connections initiated by selected Pods. This is useful when an application should communicate only with approved services or external destinations.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-api-egress
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
  - Egress
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: db
    ports:
    - protocol: TCP
      port: 5432

Once egress isolation applies to the selected Pods, traffic must match an allowed egress rule. Be careful with DNS: a default-deny egress policy can block DNS resolution unless DNS traffic is explicitly permitted.

8. Default-Allow Behavior

If no NetworkPolicy selects a Pod for a particular traffic direction, that direction is non-isolated and traffic is allowed by default, subject to other cluster controls. Isolation is applied separately for ingress and egress.

Situation

Effect

No policy selects Pod for ingress

Ingress is not isolated by NetworkPolicy.

A policy selects Pod for ingress

Ingress becomes isolated; allowed traffic must match at least one applicable ingress rule.

No policy selects Pod for egress

Egress is not isolated by NetworkPolicy.

A policy selects Pod for egress

Egress becomes isolated; allowed traffic must match at least one applicable egress rule.

9. Default Deny Policies

Deny All Ingress

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

Deny All Egress

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

Deny All Ingress and Egress

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

A common production pattern is to start with explicit isolation and then add narrowly scoped allow policies. This approach reduces accidental exposure, but it requires careful planning for DNS, monitoring, service dependencies, and external APIs.

10. Combining Multiple NetworkPolicies

NetworkPolicies are additive for allowed traffic. When multiple policies select a Pod, traffic is allowed if it matches at least one applicable rule from the relevant policies. Adding another restrictive policy does not override an existing allow rule.

This means NetworkPolicy design should be considered as a set of cumulative permissions rather than a conventional first-match firewall rule list.

11. podSelector vs namespaceSelector

A podSelector identifies Pods by labels. A namespaceSelector identifies namespaces by labels. They can also be combined.

ingress:
- from:
  - namespaceSelector:
      matchLabels:
        team: payments
    podSelector:
      matchLabels:
        app: api

When namespaceSelector and podSelector are specified in the same from entry, the intent is to select Pods with the specified labels within namespaces matching the namespace selector. Keeping selectors explicit helps avoid unintentionally broad access.

12. Allow Traffic from Another Namespace

Cross-namespace access is a frequent source of confusion. A Pod selector by itself is namespace-scoped to the namespace containing the policy. To select Pods in other namespaces, use namespaceSelector, often together with podSelector.

ingress:
- from:
  - namespaceSelector:
      matchLabels:
        environment: production
    podSelector:
      matchLabels:
        app: frontend

This example targets frontend Pods in namespaces labeled environment=production.

13. Using ipBlock

ipBlock is used when traffic should be allowed based on an IP range rather than Pod or namespace labels.

egress:
- to:
  - ipBlock:
      cidr: 10.20.0.0/16
      except:
      - 10.20.5.0/24
  ports:
  - protocol: TCP
    port: 443

IP-based policies require careful consideration of the actual network path and how the cluster networking implementation handles traffic, NAT, and external destinations.

14. Ports and Protocols

NetworkPolicy rules can restrict traffic by protocol and port. Common examples include TCP 80/443 for HTTP/HTTPS, TCP 5432 for PostgreSQL, and TCP 3306 for MySQL.

ports:
- protocol: TCP
  port: 443

Do not assume that allowing a Service's port automatically means every application dependency is allowed. NetworkPolicy is evaluated against network traffic to or from the selected Pods.

15. Real-World Three-Tier Application

Consider a production application with three logical tiers:

  • Frontend: receives user requests.

  • API: performs business logic.

  • Database: stores application data.

A sensible communication model is:

Internet / Gateway
      |
      v
  Frontend Pods
      |
      | TCP 8080
      v
      API Pods
      |
      | TCP 5432
      v
  Database Pods

The objective is not to make every Pod reachable. Instead, each tier should communicate only with the workloads and destinations it actually requires.

Allow Frontend → API

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-from-frontend
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080

Allow API → Database

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-from-api
spec:
  podSelector:
    matchLabels:
      app: db
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: api
    ports:
    - protocol: TCP
      port: 5432

With appropriate default-deny policies, the frontend cannot directly connect to the database unless another policy explicitly permits that path.

16. NetworkPolicy and Services

A Service provides a stable endpoint for reaching a set of backend Pods. NetworkPolicy controls network traffic involving the Pods selected by policies. Therefore, a Service and a NetworkPolicy solve different problems.

Component

Primary responsibility

Service

Stable service discovery and routing to backend Pods.

NetworkPolicy

Controls which network connections are allowed.

Pod

Runs the application workload and has a Pod IP.

EndpointSlice

Tracks the endpoints backing a Service.

Network plugin/CNI

Provides networking and, where supported, enforces NetworkPolicy.

17. NetworkPolicy and DNS

DNS is one of the most common issues after introducing egress restrictions. Kubernetes workloads frequently use DNS to resolve Service names. If a namespace receives a default-deny egress policy, DNS traffic can be blocked.

A DNS allow rule should be designed for the DNS service used by the cluster and verified against the actual DNS implementation and namespace labels in that environment. Do not blindly copy a DNS policy without checking the cluster configuration.

18. NetworkPolicy Does Not Provide Everything

  • It is not an application-layer authorization system.

  • It does not replace TLS or encryption.

  • It does not replace identity and authentication.

  • It does not automatically create a firewall implementation.

  • It does not guarantee identical behavior across all networking implementations for every protocol.

NetworkPolicy is a Layer 3/4 traffic-control mechanism. Higher-level controls are needed when authorization depends on HTTP paths, application identities, tokens, or business rules.

19. Troubleshooting NetworkPolicy

Problem 1: Policy Has No Effect

First verify that the cluster networking implementation supports NetworkPolicy enforcement.

kubectl get networkpolicy
kubectl describe networkpolicy <policy-name>

The NetworkPolicy object can exist in the API even when the underlying networking implementation does not enforce it.

Problem 2: Traffic Is Blocked Unexpectedly

  1. Check which NetworkPolicies select the source and destination Pods.

  2. Inspect Pod labels.

  3. Check namespace labels if namespaceSelector is used.

  4. Verify the destination port and protocol.

  5. Check whether an egress policy blocks the source Pod.

  6. Check whether an ingress policy blocks the destination Pod.

  7. Test DNS separately if the application uses Service names.

kubectl get pods --show-labels
kubectl get namespaces --show-labels
kubectl get networkpolicy -A
kubectl describe networkpolicy <policy-name>

Problem 3: DNS Stops Working

Look for a default-deny egress policy and verify that the required DNS traffic is allowed. Test name resolution from the affected Pod before investigating the application itself.

Problem 4: A Cross-Namespace Rule Does Not Match

Verify that the namespace has the expected labels and that the Pod labels are correct. Remember that selector scope matters.

20. Common Mistakes

  • Creating a NetworkPolicy without confirming NetworkPolicy support in the networking implementation.

  • Using an overly broad podSelector.

  • Forgetting that ingress and egress isolation are independent.

  • Applying default-deny egress without planning DNS.

  • Assuming a Service definition automatically bypasses NetworkPolicy.

  • Using namespaceSelector without controlling namespace labels.

  • Assuming NetworkPolicy is a first-match firewall rule system.

  • Testing only from one source Pod and assuming all paths behave the same.

  • Using labels that are not consistently managed across workloads.

21. Best Practices

  1. Start by documenting the intended communication graph between workloads.

  2. Use meaningful and stable application labels.

  3. Prefer least-privilege allow rules over broad network access.

  4. Use namespace labels deliberately when implementing cross-namespace policies.

  5. Introduce default-deny policies gradually and test application dependencies.

  6. Plan DNS access before enforcing egress isolation.

  7. Keep policies close to the workloads and document their purpose.

  8. Test both allowed and denied paths.

  9. Verify behavior with the actual networking implementation used by the cluster.

  10. Treat NetworkPolicy as defense in depth, not as the only security control.

22. Hands-On Lab

Step 1: Create an NGINX Deployment

kubectl create deployment nginx --image=nginx
kubectl expose deployment nginx --port=80

Step 2: Test Access

kubectl run busybox --rm -ti --image=busybox -- /bin/sh
wget --spider --timeout=1 nginx

Step 3: Apply an Access Policy

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: access-nginx
spec:
  podSelector:
    matchLabels:
      app: nginx
  ingress:
  - from:
    - podSelector:
        matchLabels:
          access: "true"

Apply it with kubectl apply -f policy.yaml. A Pod without the access=true label should no longer be able to reach the selected NGINX Pods, while a test Pod with that label should be allowed, assuming the cluster networking implementation enforces NetworkPolicy.

Step 4: Test with the Correct Label

kubectl run busybox --rm -ti --labels="access=true" --image=busybox -- /bin/sh
wget --spider --timeout=1 nginx

23. Production Design Example

A production namespace might use a default-deny baseline and then explicitly allow required paths:

Frontend  -> API       TCP 8080
API       -> Database  TCP 5432
API       -> DNS       DNS service
API       -> External API TCP 443
Monitoring -> Metrics endpoints

The exact policies should be derived from the application's real dependency graph. Avoid copying a generic policy into production without testing its effects.

24. NetworkPolicy vs Traditional Firewall

Aspect

NetworkPolicy

Traditional network firewall

Primary scope

Kubernetes Pods and network identities/selectors

Network segments, interfaces, IPs, ports, and other infrastructure

Configuration model

Kubernetes API objects

Firewall-specific configuration

Workload awareness

Pod/namespace selectors can express workload intent

Often infrastructure/IP oriented

Typical layer

L3/L4 traffic control

Depends on firewall technology

Implementation

Enforced by supported networking implementation

Enforced by firewall infrastructure/software

They are complementary. NetworkPolicy can provide workload-level segmentation while broader network controls protect cluster, node, VPC, and external boundaries.

25. Interview Questions

Q1. What is Kubernetes NetworkPolicy?

It is a Kubernetes API resource that specifies allowed network traffic for selected Pods at the IP/port level, including ingress and egress traffic.

Q2. What happens if no NetworkPolicy exists?

For a given traffic direction, Pods are not isolated by NetworkPolicy when no policy selects them for that direction.

Q3. What does podSelector: {} mean?

It selects all Pods in the policy's namespace.

Q4. Are NetworkPolicies first-match rules?

No. Applicable policies combine their allowed traffic; traffic is allowed when it matches at least one applicable allow rule.

Q5. Why can DNS break after applying default-deny egress?

Because DNS queries are outbound traffic. If egress is isolated and DNS is not explicitly allowed, name resolution can fail.

Q6. Does creating a NetworkPolicy guarantee enforcement?

No. The cluster networking implementation must support and enforce NetworkPolicy.

Q7. What is the difference between ingress and egress?

Ingress controls traffic entering selected Pods; egress controls traffic leaving selected Pods.

26. Production Checklist

  • NetworkPolicy enforcement support verified.

  • Application communication paths documented.

  • Ingress and egress requirements documented.

  • Default-deny strategy evaluated.

  • DNS requirements tested.

  • Namespace and Pod labels controlled.

  • Cross-namespace access reviewed.

  • Allowed and denied paths tested.

  • Policies reviewed as application dependencies change.

  • NetworkPolicy combined with application and infrastructure security controls.

27. Summary

Kubernetes NetworkPolicy is one of the key building blocks for workload network segmentation. It allows teams to move from unrestricted Pod connectivity toward explicit, application-aware communication rules.

The most important concepts are podSelector, ingress, egress, namespaceSelector, ipBlock, ports, policyTypes, and the additive behavior of multiple policies. For production environments, the strongest approach is usually to define the required communication paths, establish an appropriate isolation baseline, explicitly allow necessary traffic, and continuously test the resulting behavior.

Most importantly, remember that NetworkPolicy is an API contract whose enforcement depends on the cluster's networking implementation. Always validate the behavior of the actual CNI/networking solution used by your Kubernetes environment.

28. Related BitCodeMatrix Topics

  • Kubernetes Networking Explained

  • Kubernetes Service Explained: ClusterIP, NodePort and LoadBalancer

  • Kubernetes Gateway API Explained: The Modern Approach to Application Traffic

  • Kubernetes DNS and Service Discovery

  • Kubernetes Security Fundamentals

  • Kubernetes RBAC Explained

  • Kubernetes Ingress Explained

  • Kubernetes CNI and Cluster Networking

Official References

Kubernetes documentation: Network Policies — https://kubernetes.io/docs/concepts/services-networking/network-policies/

Kubernetes documentation: Declare Network Policy — https://kubernetes.io/docs/tasks/administer-cluster/declare-network-policy/

Kubernetes API Reference: NetworkPolicy — https://kubernetes.io/docs/reference/kubernetes-api/networking/network-policy-v1/

Kubernetes documentation: Services, Load Balancing, and Networking — https://kubernetes.io/docs/concepts/services-networking/