CNCFKubernetesContainer OrchestrationIntermediate24 min read

What Is Network Policies in Networking?

Also known as: Network Policies, Kubernetes, CKA, CNCF, pod security

Reviewed byJohnson Ajibi· Senior Network & Security Engineer · MSc IT Security
On This Page

Quick Definition

Network Policies are rules in Kubernetes that decide which pods can talk to each other and what traffic is allowed in or out. Think of them as a set of permission slips that control the flow of data between different parts of an application. They help keep your cluster secure by preventing unauthorized connections.

Must Know for Exams

The Certified Kubernetes Administrator (CKA) exam heavily tests Network Policies. They are a core networking topic in the CNCF curriculum. In the CKA exam, candidates must demonstrate the ability to create, apply, and troubleshoot Network Policies. The exam objectives explicitly include: understand how to configure network policies to control ingress and egress traffic, and how to use pod and namespace selectors.

CKA questions often present a scenario where a cluster has a security requirement, and you must write a Network Policy to enforce it. For example, you might be told to deny all ingress traffic to a specific deployment, or to allow traffic only from a specific namespace. You need to be comfortable with the YAML manifest structure, including the apiVersion, kind, metadata, and spec fields. You must also know the difference between podSelector and namespaceSelector, and how the podSelector, ingress, and egress rules interact.

Another common exam task is to troubleshoot why a policy is not working. For instance, a pod might be unreachable even though you think you wrote the policy correctly. You need to check if the CNI plugin supports policies, if the selectors match the intended pods, and if the policyTypes field is correctly set. The exam may also test your understanding of the default deny behavior. When you create a policy that selects a specific pod, all traffic not explicitly allowed by that policy is denied. This is a frequent point of confusion for test-takers.

The CKA exam is performance-based, meaning you are given a live cluster and must perform tasks. You cannot just answer theoretical questions; you must actually write YAML files, apply them with kubectl apply, and verify the results using kubectl describe networkpolicy or kubectl get networkpolicy. Therefore, hands-on practice with Network Policies is essential for exam success. Understanding the concepts deeply, including edge cases like multiple selectors and IPBlocks, will give you the confidence to handle any scenario the exam throws at you.

Simple Meaning

Imagine you are working in a large office building with many different departments. Each department has its own team, and each team works in a separate room. Some teams need to share information, like the sales team sharing customer details with the billing team. Other teams, like human resources, should only talk to specific groups and keep their data private. Without any rules, anyone could walk into any room and take any file. This would be chaos and a security nightmare.

Network Policies in Kubernetes are like a set of access badges and hallway rules for your applications. Every application in Kubernetes runs inside a pod, which is like a small virtual computer. Normally, any pod can talk to any other pod unless you explicitly block it. This is like leaving every office door wide open. Network Policies allow you to say, for example, only the frontend web server pods can talk to the backend database pods, and no other pod can access the database. You can also control traffic coming into the cluster from outside (ingress) and traffic leaving the cluster (egress).

These policies work by labeling pods and then writing rules that select pods based on those labels. Labels are like name tags that group pods together. You might label all database pods with a tag that says role: database, and all web server pods with role: frontend. Your Network Policy then says: allow traffic from pods with role: frontend to pods with role: database on port 5432. Any pod without the frontend label cannot reach the database. This is similar to a building security guard checking badges at every door and only letting people through if their badge has the right permissions. Network Policies give you precise control, making your Kubernetes cluster much safer and more organized.

Full Technical Definition

A Kubernetes Network Policy is a specification that defines how a group of pods is allowed to communicate with other network endpoints. It is a resource in the networking.k8s.io/v1 API group. Network Policies are implemented by a Container Network Interface (CNI) plugin that supports them, such as Calico, Cilium, Weave Net, or the Antrea plugin. If the CNI plugin does not support Network Policies, the resources can be created but will have no effect.

A Network Policy consists of three main sections: podSelector, policyTypes, and rules (ingress and egress). The podSelector uses label selectors to determine which pods the policy applies to. If the podSelector is empty, it applies to all pods in the namespace. The policyTypes field can include Ingress, Egress, or both. If you do not specify policyTypes, only ingress rules are enforced by default. The ingress rules define allowed incoming traffic to the selected pods, using rules that can specify sources (pods, namespaces, IP blocks) and ports. The egress rules define allowed outgoing traffic from the selected pods, specifying destinations and ports.

Each rule can use one or more selectors. IPBlock selectors allow you to define CIDR ranges for allowed traffic, which is useful for controlling access to external services or VPNs. NamespaceSelector selects all pods within a particular namespace. PodSelector selects pods based on their labels. You can combine selectors using logical AND, so a rule might require that traffic comes from a pod with label app: frontend AND from a namespace with label environment: production. This granularity allows for very precise security controls.

Network Policies are stateful in a limited way. They do not track connection state themselves, but the underlying CNI plugin often implements connection tracking to allow return traffic. For example, if you allow a pod to make an outbound connection, the return traffic is typically allowed back automatically. However, you must explicitly allow all desired traffic; anything not allowed is denied by default. This is a key security principle: default deny, then explicitly allow what is needed.

In real IT environments, Network Policies are essential for microservices security. They enable a zero-trust network model within the cluster, meaning no pod trusts any other pod until proven otherwise. This reduces the blast radius of a security breach. For example, if a web server pod is compromised, a well-designed Network Policy prevents the attacker from reaching the database or other internal services. Policies are also used to enforce compliance with regulations like PCI-DSS or HIPAA by isolating sensitive data pods.

Real-Life Example

Think of a busy hospital with different wards, offices, and specialized rooms. The entire hospital has a main entrance, but not everyone can go everywhere. Doctors, nurses, patients, visitors, and administrative staff all need different levels of access. Now, imagine the hospital as your Kubernetes cluster, and each care unit or office as a pod.

A Network Policy is like the hospital's access control system. The front door (ingress) has a security guard who checks badges. But inside, there are also badge readers on every door to specific wards. The pharmacy can only be accessed by pharmacists and doctors with a specific clearance. The operating theater is restricted to surgical teams. The patient records room is only for attending physicians and authorized IT staff. No one else can enter, even if they have a hospital badge.

In this analogy, the badge is a pod label. Pods have labels like role: doctor or role: pharmacist. The Network Policy rules are the door readers. For the pharmacy door, the rule says: only allow entry to pods with label role: pharmacist or role: doctor. If a pod with label role: visitor tries to enter, the door remains locked. Similarly, egress rules control who can leave certain areas. For example, a patient pod might only be allowed to send data to a monitoring station and not to the internet.

This mapping shows exactly how Network Policies work. They are the badge readers and security guards for your application traffic, ensuring that only the right pods can talk to the right services, on the right ports, keeping the whole system safe and organized.

Why This Term Matters

In modern cloud-native environments, applications are broken into many small, independent microservices running in containers. These microservices need to communicate over the network, but without controls, any compromised service can immediately attack other services. Network Policies provide the necessary segmentation and isolation to enforce the principle of least privilege. They are a fundamental security control for any production Kubernetes cluster.

For system administrators and DevOps engineers, Network Policies reduce the attack surface. If an attacker gains access to one pod, policies limit what else they can reach. For example, a frontend web server might need to talk to a database but not to other internal services. With a proper policy, even if the frontend is compromised, the database and other sensitive systems remain protected. This containment is critical for preventing lateral movement during a security incident.

Network Policies also simplify compliance. Many regulations require network segmentation between different types of data. For example, payment card information must be isolated from other data. By applying Network Policies that separate payment-processing pods from the rest of the cluster, you can demonstrate compliance with PCI-DSS and similar standards. Auditors can easily review the policies as part of their assessment.

Beyond security, Network Policies improve network performance by reducing unnecessary traffic. When pods are isolated, they do not broadcast to the entire cluster, reducing noise and improving resource utilization. They also make the system easier to understand and debug, because the allowed communication paths are explicitly defined in code. This documentation of intent helps new team members understand the architecture quickly.

Without Network Policies, your Kubernetes cluster is like a house with no internal walls. Everything is open, and a problem in one room quickly spreads to the whole house. Network Policies are the walls and doors that give you control, safety, and peace of mind.

How It Appears in Exam Questions

Exam questions about Network Policies fall into several distinct patterns. The most common is configuration questions. These ask you to create a Network Policy that achieves a specific access control goal. For example, you might be given a YAML file that is incomplete, and you need to fill in the correct podSelector or ingress rules. Alternatively, you might be asked to write the entire policy from scratch. The question might specify: create a network policy named allow-frontend that allows traffic from pods with label app: frontend to pods with label app: backend on port 8080.

Another pattern is troubleshooting questions. The exam might present a scenario where an application is not working correctly, and you need to identify that a Network Policy is blocking the required traffic. For instance, a web server cannot reach the database. You would inspect the existing policies with kubectl describe networkpolicy and look for missing rules. You might find that the ingress rule on the database pod does not include the source selector for the web server.

Scenario-based questions describe a real-world situation and ask you to propose the correct policy. For example: you have a three-tier application with frontend, backend, and database tiers. The frontend must be accessible from the internet via an Ingress controller. The backend should only accept traffic from the frontend. The database should only accept traffic from the backend. Create the necessary Network Policies. This type of question tests your ability to design a multi-policy security architecture.

Architecture questions may ask you to explain the effect of a given Network Policy. You might see a YAML manifest and be asked: which pods are affected by this policy? What traffic is allowed or denied? You need to read the selectors and rules carefully. A common trick is that a policy with only an ingress rule and no egress rule still allows default egress for the selected pods. You need to understand that policyTypes default is Ingress only.

Finally, some questions test your knowledge of edge cases. For example, what happens if you have two Network Policies that apply to the same pod? The answer is that both policies are combined with a logical AND, meaning only traffic that is allowed by both policies is permitted. Another edge case is when a policy has an empty podSelector, which applies to all pods in the namespace. This is a common way to set a default deny-all policy for a namespace.

Study cncf-cka

Test your understanding with exam-style practice questions.

Practise

Example Scenario

You are a Kubernetes administrator for an e-commerce company. The company has a cluster running their online store. The store has three main components: a frontend web server, a payment processing service, and a customer database. The frontend needs to accept traffic from the public internet via an Ingress controller. The payment service must only receive requests from the frontend, never directly from the internet or from any other service. The database must only accept connections from the payment service on port 5432. No other pod in the cluster should be able to reach the database or the payment service.

To enforce this, you create three Network Policies. First, you create a policy that selects the database pods (with label app: database) and allows ingress only from pods with label app: payment on port 5432. Second, you create a policy for the payment pods (label app: payment) that allows ingress only from pods with label app: frontend on port 3000. Third, you create a policy for the frontend pods that allows ingress from the Ingress controller namespace. Additionally, you might add an egress policy on the frontend to ensure it can only talk to the payment service, and on the payment service to only talk to the database.

By applying these policies, you have created a secure, isolated environment. Even if the frontend is compromised, the attacker cannot directly access the database. The payment service acts as a secure gateway. This scenario demonstrates how Network Policies are used to implement defense in depth and microsegmentation in a real microservices architecture.

Common Mistakes

Thinking Network Policies are enabled by default in all Kubernetes clusters.

Network Policies are only enforced if the cluster's CNI plugin supports them. Common plugins like Flannel do not support Network Policies. If you apply a policy in a cluster using Flannel, it will be stored but will have no effect on traffic. You must use a compatible CNI plugin such as Calico, Cilium, or Weave Net.

Before relying on Network Policies, check which CNI plugin your cluster uses. If it does not support policies, either switch to a compatible plugin or use another method like service mesh for traffic control.

Believing that a Network Policy allows traffic by default and only blocks what is specified.

Network Policies use a default-deny model. Once you apply a policy that selects a pod, all traffic that is not explicitly allowed by that policy is denied. This applies even if you only define ingress rules; egress traffic is also denied if you include Egress in policyTypes. Many beginners assume policies work like a firewall whitelist, but they actually work as a whitelist that blocks everything else.

Always remember that the first rule of a Network Policy is to deny everything unless allowed. When you add a policy to a pod, you must explicitly allow all the traffic you need, including return traffic if your CNI plugin does not handle it automatically.

Confusing podSelector with namespaceSelector in the from section.

A podSelector inside a rule selects pods based on labels within the same namespace as the policy, unless a namespaceSelector is also specified. If you want to allow traffic from pods in a different namespace, you must either use a namespaceSelector alone or combine both a namespaceSelector and a podSelector. Simply using a podSelector without a namespaceSelector will not match pods in other namespaces.

To allow traffic from a specific namespace, add a namespaceSelector along with the podSelector. For example, from: - namespaceSelector: matchLabels: environment: production podSelector: matchLabels: app: frontend. This ensures you select the correct pods in the correct namespace.

Forgetting that the policyTypes field must be explicitly set to include both Ingress and Egress, or that default is only Ingress.

If you do not specify policyTypes in your Network Policy manifest, Kubernetes defaults to only Ingress. This means any egress rules you define will be ignored. You must explicitly include Egress in the policyTypes array if you want to control outbound traffic. This is a common source of bugs where egress restrictions do not apply as expected.

Always explicitly set the policyTypes field in your Network Policy manifest, even if you only need one direction. For example, policyTypes: [Ingress, Egress]. This makes your intent clear and avoids reliance on default behavior.

Exam Trap — Don't Get Fooled

An exam question gives you a Network Policy that only has an ingress rule but no egress rule, and asks whether a pod selected by that policy can make outbound connections to the internet. Remember that if a Network Policy selects a pod and you only include Ingress in policyTypes, egress traffic is completely unrestricted. The pod can still make outbound connections.

Conversely, if you include Egress in policyTypes but do not define any egress rules, all egress traffic is denied. Always check the policyTypes field first. When reading a policy, look at what is explicitly set, and know the defaults: no policyTypes means only Ingress is enforced.

Commonly Confused With

Network PoliciesvsNetwork Policies vs. Kubernetes Network Plugins (CNI)

Network Policies are rules that define allowed traffic, while CNI plugins are the software that actually enforces those rules. A CNI plugin like Calico implements both networking and policy enforcement. Without a compatible CNI plugin, Network Policies are just configuration files that do nothing.

Think of Network Policies as traffic laws and the CNI plugin as the police officer who enforces them. You can write all the laws you want, but without an officer on the street, traffic will ignore them.

Network PoliciesvsNetwork Policies vs. Service Mesh (e.g., Istio)

Both control traffic, but they work at different layers. Network Policies operate at the network layer (L3/L4, covering IP addresses and ports). A service mesh like Istio operates at the application layer (L7), allowing control based on HTTP methods, paths, headers, and other application-level details. Network Policies are simpler and lighter, while service meshes provide more granular control at the cost of complexity.

A Network Policy is like a bouncer at the club door checking IDs (IP and port). A service mesh is like a host inside who checks membership cards and decides which floor you can go to based on your drink order (HTTP details).

Network PoliciesvsNetwork Policies vs. Security Groups (AWS, Azure, GCP)

Cloud security groups protect virtual machines or network interfaces, while Network Policies protect pods inside Kubernetes. Security groups are attached to instances or subnets in the cloud provider's network. Network Policies are Kubernetes-native and are enforced within the cluster's overlay network, independent of the underlying cloud provider.

A security group is like a gate at the entrance of a building (the VM). A Network Policy is like a badge reader on every internal door inside the building (the pod). Both control access, but at different levels.

Step-by-Step Breakdown

1

Identify the pods to protect

The first step is to decide which pods you want to secure. In Kubernetes, you select pods using labels. For example, if you want to protect the database, you identify the label that the database pods have, such as role: database. This label will be used in the podSelector of the Network Policy.

2

Define the policy type

Decide whether you need to control incoming traffic (Ingress), outgoing traffic (Egress), or both. Set the policyTypes field accordingly. For example, if you only need to control who can access the database, you would include Ingress. If you also need to control what the database can connect to, include Egress. This step determines the scope of the policy.

3

Write the ingress rules

Specify which sources are allowed to send traffic to the selected pods. You can use podSelector, namespaceSelector, or ipBlock. For example, to allow traffic only from the frontend pod with label app: frontend, you write an ingress rule with a podSelector that matches that label. You also specify the allowed ports, e.g., port 5432 for PostgreSQL.

4

Write the egress rules

If you included Egress in policyTypes, define which destinations the selected pods are allowed to reach. Similar to ingress, you can use podSelector, namespaceSelector, or ipBlock. For example, a payment service might only be allowed to egress to a database pod on port 5432 and nothing else.

5

Create the Network Policy manifest

Put everything together in a YAML file. The manifest includes apiVersion: networking.k8s.io/v1, kind: NetworkPolicy, metadata with name and namespace, and spec with podSelector, policyTypes, and the ingress/egress rules. Apply the manifest using kubectl apply -f policy.yaml. The CNI plugin will then enforce the rules.

6

Verify the policy is working

Use kubectl get networkpolicy to list policies, and kubectl describe networkpolicy policy-name to see the details. Then, test connectivity by running a temporary pod with tools like curl or telnet, and verify that allowed traffic passes while denied traffic is blocked. If connectivity fails, check pod labels, selectors, and the CNI plugin compatibility.

Practical Mini-Lesson

Network Policies are one of the most important security features in Kubernetes, and mastering them is essential for any administrator. In practice, you will rarely run a production cluster without them. The first thing to know is that Network Policies are namespace-scoped. That means you create a policy within a specific namespace, and it only affects pods in that namespace. To protect pods in multiple namespaces, you need separate policies in each.

When configuring a policy, the podSelector is key. If you leave it empty (e.g., podSelector: {}), the policy applies to all pods in the namespace. This is a common way to set a default deny-all policy for an entire namespace. For example, you might want to deny all ingress traffic to every pod in the namespace, then create additional policies that open specific paths for specific pods. This is a powerful security pattern.

The ingress and egress rules use a set of selectors that can be combined. When you specify both a namespaceSelector and a podSelector in the same from or to block, the rule applies only to pods that match both selectors. This is a logical AND. For example, from: - namespaceSelector: matchLabels: environment: production podSelector: matchLabels: app: frontend means only pods with label app: frontend in namespaces with label environment: production are allowed. If you want an OR condition, you need multiple entries in the from array.

Ports are specified using the ports field within each rule. You can specify a protocol (TCP, UDP, or SCTP) and a port number or port name. It is best practice to use port names that correspond to the container's port definitions, as this makes the policy more readable and maintainable. For example, you might define a port named http on port 80 in the container spec, and then use port: http in the policy.

A common advanced use case is controlling traffic to external services using ipBlock. For example, you might want to allow a pod to reach only a specific external API endpoint for license validation. You would define the egress rule with an ipBlock that includes the API server's CIDR. Be careful with multiple ipBlock entries, as they are evaluated with an OR logic.

Another practical consideration is that Network Policies can be difficult to debug. When traffic is blocked, you often see a timeout rather than a clear error. Tools like kubectl exec into a pod and run tcpdump or netcat can help. Also, understand that the CNI plugin may have its own logging that can show policy denials. For example, Calico provides calicoctl to troubleshoot policy issues.

Finally, remember that Network Policies are additive. If you have two policies that both apply to the same pod, the pod's effective policy is the union of all rules that allow traffic, but only if the traffic is allowed by at least one policy. However, if one policy denies traffic and another allows it, the rule is not simple; in practice, because all policies default to deny, any rule that matches and allows traffic will override the default deny, so having multiple policies typically expands allowed traffic. The key is the default deny applies where no rule matches. So if one policy allows traffic from source A, and another policy allows traffic from source B, both are allowed. But if no policy allows source C, it is denied. This is important for the exam.

Memory Tip

Remember the three S's of Network Policies: Selector, Source, and Service. Selector picks the pods to protect, Source defines who is allowed in, and Service defines which port is allowed. If you forget, think Default Deny, then allow what is needed.

Covered in These Exams

Related Glossary Terms

Frequently Asked Questions

Can I use Network Policies to block traffic between pods in the same namespace?

Yes. You create a Network Policy that selects the source pods or the destination pods and uses rules to deny traffic. However, since Network Policies use a whitelist model, you block by not allowing. If you want to deny all traffic between two specific pods, you would create a policy that does not include a rule for that traffic, so it is denied by default.

What happens if I apply a Network Policy but my CNI plugin does not support it?

The Network Policy resource will be created in the cluster, but it will have no effect on traffic. Your cluster will still allow all pod-to-pod communication. You must use a CNI plugin that supports Network Policies, such as Calico, Cilium, or Weave Net, for the policies to be enforced.

Can Network Policies control traffic to and from services outside the Kubernetes cluster?

Yes, using the ipBlock selector in ingress and egress rules. You can specify CIDR ranges to allow traffic to or from external IP addresses. This is commonly used to allow pods to reach specific external APIs or databases while blocking all other external traffic.

Is it possible to allow all traffic except certain types using Network Policies?

No, Network Policies are whitelist-based. You cannot specify a deny rule for a specific source or destination. You must explicitly allow all traffic you want, and everything else is denied by default. To block specific traffic, you create a policy that allows everything else, but that is not the intended use case.

Do Network Policies affect traffic within the same pod?

No, Network Policies apply to traffic between pods. Traffic within the same pod (e.g., between containers in the same pod) is not affected by Network Policies because containers in a pod share the same network namespace.

Can I have multiple Network Policies on the same pod?

Yes. Multiple policies can select the same pod. The effective rules for the pod are the union of all allowed rules from all policies. However, if a traffic pattern is not allowed by any policy, it is denied. There is no conflict resolution needed because policies only add allowed traffic; they cannot deny traffic that another policy allows.

Summary

Network Policies are a fundamental security resource in Kubernetes that control which pods can communicate with each other and with external networks. They work by selecting pods based on labels and defining ingress and egress rules that specify allowed sources, destinations, and ports. The key principle is default-deny: any traffic not explicitly allowed is blocked. This makes them a powerful tool for implementing microsegmentation, zero-trust networking, and compliance in cloud-native environments.

For the CKA exam, you must be comfortable writing, applying, and troubleshooting Network Policies. Understand the role of the CNI plugin, the importance of the policyTypes field, and the behavior of combined selectors. Practice creating policies for common scenarios such as isolating a database, allowing traffic from a specific namespace, or controlling external access. Avoid common mistakes like assuming policies are always active, confusing selectors, or forgetting that default is deny.

Network Policies are not just an exam topic; they are a daily necessity for securing production Kubernetes clusters. By mastering them, you ensure that your applications are safe from unauthorized access and that your infrastructure meets security best practices. Remember the three S's: Selector, Source, and Service, and always think about what traffic you need to allow before you create the policy.