Network Policies for Security in Kubernetes
Learn how Network Policies turn a wide-open cluster network into a set of clear, narrow paths, so that a problem in one application cannot easily spread to the others.
Imagine an apartment building where every door inside is unlocked and every hallway connects to every flat. A neighbour can walk into any home, and a stranger who slips in through the front entrance can wander freely from floor to floor. Nobody designed it that way on purpose. It is simply how the building was built, because locks were never fitted. A Kubernetes cluster starts out just like that building. Every pod can talk to every other pod. Network Policies are the locks and the hallway doors: they let you say exactly who may visit whom, and they shut everything else.
1What Is a Network Policy?
A Network Policy is a set of rules that says which pods may send traffic to which other pods, namespaces, and addresses.
The Simple Definition
A Network Policy is an object you create in Kubernetes that describes allowed network connections for a group of pods. It picks the pods it protects using labels, and then lists which sources may connect to them, which destinations they may connect to, and on which ports. Anything not listed is blocked for those pods.
The important word is allowed. Network Policies are written as lists of permitted paths. You do not write a rule that says block this. Instead, you write rules that say allow this, and once a pod is covered by a policy, everything that is not allowed is refused. This design is simple and safe, because forgetting a rule leads to a closed door rather than an open one.
Think of a guest list at a private party. The doorkeeper does not keep a list of people who are banned. The doorkeeper keeps a list of people who are invited, and anyone whose name is not on it stays outside. A Network Policy is the guest list for a group of pods.
What Network Policies Control
Network Policies work at the level of network connections between pods, using addresses, ports, and protocols. They control traffic coming into a pod, called ingress, and traffic going out of a pod, called egress. They do not read the content of the traffic, they do not check who the user is, and they do not encrypt anything. They are a fence, not a guard who reads letters.
A Network Policy answers one question: may this connection be opened at all? It is one of the most effective ways to limit how far an attacker can move once they get into a single pod.
Where Network Policies Fit in a Security Plan
Security in Kubernetes is built in layers, and no single layer is enough. Access control decides who may talk to the API. Image scanning decides what software may run. Pod security settings decide what a container may do on its node. Network Policies decide which containers may talk to each other. Each layer catches failures of the others, and together they make a break-in harder to achieve and easier to contain.
Network Policies are especially valuable because they still work after a break-in has happened. Many defences try to keep attackers out. Policies assume that one day something will get in, and they limit what it can reach. This assumption, sometimes called assume breach, is the mindset of mature security teams, and Network Policies are one of its most practical tools.
2Why Pods Need Fences
By default, the Kubernetes network is completely open, and that openness is a security risk.
The Flat Network
When Kubernetes was designed, one of its goals was to make networking simple for developers. Every pod gets its own address, and every pod can reach every other pod directly, whichever namespace or computer it lives on. This is called a flat network. It removes a great deal of complexity, because applications do not need to worry about translating addresses or opening special paths.
The cost of that simplicity is that the network offers no protection between applications. A test pod can reach the production database. A forgotten demo can reach the payment service. And if an attacker takes over one container through a software flaw, they can immediately try to reach every other pod in the cluster, scanning for weak targets.
Lateral Movement
Security teams use the term lateral movement for what happens after the first break-in. The attacker rarely wants the first machine they capture. They want what is next to it, such as databases, secret stores, and management tools. A flat network lets them move sideways with no resistance. Network Policies add resistance, so that a captured web pod can reach only the few things it legitimately needs, and nothing more.
flowchart LR
subgraph Open[Without policies]
A1[Web pod compromised] --> B1[Database]
A1 --> C1[Payment service]
A1 --> D1[Admin tools]
end
subgraph Fenced[With policies]
A2[Web pod compromised] --> B2[Only the API pod]
A2 -.blocked.-> C2[Database]
A2 -.blocked.-> D2[Payment service]
A2 -.blocked.-> E2[Admin tools]
end
A ship has watertight compartments. If one compartment floods, the doors between compartments close, and the ship stays afloat. Without them, one hole sinks everything. Network Policies are the watertight doors between your applications.
Many beginners assume that different namespaces are separated on the network. They are not. Namespaces organize objects and permissions, but pods in different namespaces can still talk freely unless a policy says otherwise.
A Short Story of a Real-Style Incident
Consider a typical story. A small company runs a public website and, in the same cluster, an internal reporting tool with access to customer records. The website uses a library with an unknown flaw. An attacker sends a crafted request and gains a shell inside a web pod. In a flat network, the attacker scans the cluster within seconds, finds the reporting tool, and downloads the records. The company learns of the breach weeks later from a customer.
In a segmented network, the same attacker gains the same shell but finds that the web pod can reach only the API pods. Scans to other addresses time out. The reporting tool is invisible. The attacker must find a second flaw in the API tier, which takes far longer and creates far more noise. The first flaw still happened, but its consequences are small.
Regulations and Segmentation
Many security standards and regulations ask organizations to separate systems that handle sensitive data from the rest of their environment. In traditional data centres, this meant separate physical networks and firewalls. In Kubernetes, Network Policies provide a comparable separation inside a shared cluster. Auditors increasingly accept well-written, version-controlled policies as evidence, provided the team can also show that enforcement is active and tested.
Preparing for such audits is easier when policies are organized by purpose and named clearly. An auditor asking how the payment workload is isolated can be shown the default deny, the specific allowed paths, and the tests that prove the rest is blocked. That story is convincing because every part of it can be verified.
3The Building Blocks You Need First
A few basic ideas make every Network Policy easier to read and write.
Pod
The smallest runnable unit in Kubernetes, with its own network address.
Label
A small name and value pair attached to an object, such as app equals web.
Selector
A way of choosing objects by their labels, for example all pods labelled app equals web.
Namespace
A named section of the cluster that groups objects together.
Service
A stable name and address that forwards traffic to a group of pods.
Port and Protocol
The numbered doorway and the language spoken, such as port 443 over TCP.
Labels Do the Heavy Lifting
Network Policies do not refer to pods by their addresses or names. Pods come and go, and their addresses change every time. Instead, policies refer to pods by labels. A policy might say that pods labelled as the database accept connections only from pods labelled as the API. As pods are replaced, the new ones carry the same labels, so the policy keeps working without any editing.
A company security policy says that only people wearing a finance badge may enter the finance office. It does not list employee names. When new staff join and receive the badge, the policy applies to them at once. Labels are the badges, and selectors are the badge checks at the door.
Ingress and Egress
Direction matters in networking. Ingress means traffic arriving at a pod from elsewhere. Egress means traffic leaving a pod towards elsewhere. A single conversation involves both: the client’s egress and the server’s ingress. A policy can control either direction, or both, and you decide separately for each.
Give pods consistent, meaningful labels, such as the application name, tier, and environment. Good labels make policies short and readable, while poor labels make policies clumsy and error-prone.
Cluster Addresses and Why They Change
Every pod receives an address from a pool that the network plugin manages. When a pod is deleted and recreated, it usually gets a new address, because the old one may already have been given to another pod. This is why writing addresses into rules is fragile for anything inside the cluster. A rule that allows one address today may allow a completely different pod tomorrow, which is both a breakage and a security hazard.
Labels avoid the problem, because they describe what a pod is rather than where it happens to be at the moment. Whenever you feel tempted to write an in-cluster address into a policy, stop and ask which label describes the workload. There almost always is one, and using it makes the policy last.
4Who Actually Enforces the Rules?
A Network Policy is only a description. Something else in the cluster must carry it out, and that something is the network plugin.
The Network Plugin
Kubernetes itself does not move network traffic. It delegates that job to a network plugin, commonly called a CNI plugin, where CNI stands for Container Network Interface. The plugin gives pods their addresses, connects them together, and, if it supports the feature, enforces Network Policies. The API server happily stores a Network Policy object, but storing is not enforcing.
If your network plugin does not support Network Policies, you can create policies and see no error at all, yet nothing is blocked. This false sense of security is one of the most serious mistakes in Kubernetes. Always confirm that your plugin enforces policies, and test it.
How Enforcement Works in General
Each node runs a piece of the plugin that watches for Network Policy objects. When a policy is created or changed, the plugin translates it into low-level filtering rules on the node, using technologies built into the operating system kernel. Packets to and from local pods are checked against those rules, and forbidden packets are dropped silently. Because the checks happen on the node where the pod runs, policies work regardless of where the other end of the connection is.
flowchart TD
U[You create a NetworkPolicy] --> API[API server stores it]
API --> AG[Network plugin agent on each node watches for changes]
AG --> RULES[Agent translates policy into kernel filtering rules]
RULES --> PKT[Packets to and from pods are checked]
PKT --> OK[Allowed packets pass]
PKT --> DROP[Other packets are dropped]
A building manager writes a rule that visitors need a pass. The rule on paper does nothing until security guards at each entrance actually check for passes. The Network Policy is the written rule, and the network plugin is the team of guards.
| Question | Where the Answer Lives |
|---|---|
| What do I want to allow? | The Network Policy object you write |
| Where is it stored? | The Kubernetes API server |
| Who blocks the traffic? | The network plugin on each node |
| How do I know it works? | Testing connections that should and should not succeed |
Choosing a Network Plugin With Security in Mind
When selecting a network plugin, security features deserve a place next to speed and simplicity. Ask whether it enforces standard Network Policies fully, including egress and namespace selectors. Ask whether it offers flow logs, since visibility is the difference between guessing and knowing. Ask whether it supports extended policies with explicit deny and cluster-wide baselines, and whether it can encrypt traffic between nodes.
Managed cloud clusters often offer several plugin choices, and some require you to switch on policy enforcement as a separate option. Read your provider’s documentation carefully, because a default setup sometimes runs without enforcement. Making the choice deliberately, early, saves a painful migration later.
5The Anatomy of a Network Policy
Every Network Policy has the same four parts, and once you know them you can read any policy.
The Four Parts
Name and namespace
Every policy lives in one namespace and only protects pods in that namespace.
Pod selector
Chooses which pods the policy protects, using labels. An empty selector chooses every pod in the namespace.
Policy types
States whether the policy governs ingress, egress, or both.
Rules
Lists of allowed sources or destinations and ports, one list for ingress and one for egress.
Reading a Policy as a Sentence
The easiest way to read a policy is as a plain sentence. For the pods labelled as the database in the shop namespace, allow incoming connections only from pods labelled as the API, only on the database port. That sentence names the protected pods, the direction, the allowed peers, and the port. If you can write the sentence, you can write the policy.
podSelector
Who is being protected.
policyTypes
Which directions are governed.
ingress
Who may connect to the protected pods, and on which ports.
egress
Where the protected pods may connect to, and on which ports.
A visitor policy for an office might read: for the finance floor, visitors are allowed only from the reception desk, only during business hours. It names the place, the direction, the allowed source, and the condition. A Network Policy has the same parts.
Before writing any policy, say it aloud in one sentence. If the sentence is long and tangled, split the policy in two. Simple policies are easier to review and safer to change.
Keeping Policy Files Readable
Policies are written as structured text, and their layout affects readability. Keep one purpose per file, or group closely related policies with clear separators. Use comments to explain unusual choices. Keep the same order of sections in every policy, such as selector first, then types, then ingress, then egress, so that reviewers know where to look.
Consistency reduces mistakes. A reviewer who has seen forty policies in the same shape spots the forty-first that differs, and that difference is often where the bug hides.
6Selecting Pods and the Idea of Isolation
A pod is either open or isolated in each direction, and a policy that selects it is what flips the switch.
Non-Isolated Pods
A pod that no policy selects is non-isolated. It accepts traffic from anywhere and can send traffic anywhere, exactly as if Network Policies did not exist. This is the starting state of every pod in a new cluster, and it remains the state of any pod that your policies do not mention.
Isolated Pods
As soon as at least one policy selects a pod for a direction, that pod becomes isolated in that direction. For ingress isolation, the pod accepts only the incoming connections that some policy allows. For egress isolation, the pod may send only the outgoing connections that some policy allows. The directions are independent: a policy that covers only ingress leaves egress fully open.
| Situation | Incoming Traffic | Outgoing Traffic |
|---|---|---|
| No policy selects the pod | Allowed from anywhere | Allowed to anywhere |
| A policy with ingress type selects the pod | Only what the policies allow | Allowed to anywhere |
| A policy with egress type selects the pod | Allowed from anywhere | Only what the policies allow |
| Policies of both types select the pod | Only what policies allow | Only what policies allow |
Consider a room with two doors, one for entering and one for leaving. Fitting a lock on the entry door does nothing to the exit door. Each door needs its own lock, and each lock needs its own guest list. Ingress and egress are the two doors.
Writing an ingress policy and assuming the pod is fully protected. Egress remains open, so a compromised pod can still send data anywhere. Decide deliberately about both directions.
Policies Do Not Cross Namespaces for Selection
A policy protects only pods in its own namespace. To protect pods in three namespaces, you need policies in each of the three. This keeps things predictable: reading the policies in a namespace tells you everything about how its pods are protected.
Thinking About Which Pods to Isolate First
Not all pods carry the same risk, so rolling out isolation in a sensible order pays off. Start with pods that hold valuable data, such as databases and secret stores, since protecting them limits the worst outcomes. Then protect pods that face the internet, since they are the most likely first point of attack. Then protect the middle tiers that connect them. Finally, cover the remaining workloads and shared services.
This order gives the largest reduction in risk for the earliest effort. It also gives your team practice on important but well-understood workloads before you tackle the messy, poorly documented ones.
7Ingress Rules: Who May Connect In
Ingress rules list the sources that are allowed to open connections to the protected pods.
Sources and Ports
An ingress rule has two optional lists. The first, called from, names the allowed sources. The second, called ports, names the allowed destination ports on the protected pod. A connection is allowed by the rule only if it matches both lists. If the from list is left out, any source is allowed for those ports. If the ports list is left out, any port is allowed from those sources.
A policy may contain several ingress rules. A connection is allowed if it matches any one of them. This makes it easy to combine separate needs, such as allowing the API pods on the database port and allowing the monitoring pods on the metrics port, in a single policy.
Database Protection
Allow incoming connections to database pods only from the API pods, and only on the database port. Every other pod in the cluster is refused, even if it lives in the same namespace.
Metrics Scraping
Allow the monitoring pods, which live in another namespace, to reach the metrics port of every application pod. Other ports stay closed to them.
Public Front End
Allow connections from anywhere to the web pods on port 443, because they serve the public. Their other ports stay closed.
A restaurant has several entry rules: customers may use the front door for the dining room, delivery drivers may use the back door for the kitchen, and only staff may use the office door. Each rule names who may use which door. Ingress rules do the same for pods and ports.
Prefer naming both the source and the port. A rule that allows any port from a trusted source is broader than needed, and that extra width is what an attacker will use.
Health Checks and Platform Traffic
Not all traffic to a pod comes from other applications. The node agent on the pod’s own computer sends health checks to see whether a pod is alive and ready. Monitoring systems and service meshes also send their own traffic. Depending on the network plugin, traffic from the local node may be allowed automatically, or it may need an explicit rule. Forgetting this can make healthy pods appear broken and cause endless restarts.
When you first apply an ingress policy to a workload with health checks, watch the pods closely. If they begin restarting and their health checks fail, check how your plugin treats traffic from the node, and add the required allowance for the node address range or for the health check port if needed.
8Egress Rules: Where Pods May Connect Out
Egress rules list the destinations that protected pods are allowed to reach.
Why Egress Matters
Many teams protect the entrances and forget the exits. Yet exits are where stolen data leaves and where a captured pod calls home to its controller. Controlling egress can stop a compromised pod from downloading harmful tools, contacting a command server, or copying customer records to an outside address. Because attackers depend on outbound connections, egress policies are among the most powerful defences.
Destinations and Ports
An egress rule has a to list and a ports list, mirroring the ingress structure. The to list names the allowed destinations, and the ports list names the allowed destination ports. A connection is allowed if it matches any egress rule of any policy selecting the pod.
Front End Talks Only to the API
Web pods may connect only to the API pods on the API port, plus the cluster’s name lookup service. They cannot reach databases directly or the open internet.
Payment Service Talks to One Provider
Payment pods may connect to the address range of a single payment provider on port 443 and nothing else outside the cluster.
Batch Jobs Talk Only to Storage
A nightly job may connect to one storage service and a message queue, and it is blocked from everything else.
A company may let staff receive visitors, but also restrict which phone numbers the office phones may call. If a stolen laptop tries to phone an unknown number, the call simply does not connect. Egress rules are the restrictions on outbound calls.
The moment you restrict egress, pods lose the ability to look up names unless you explicitly allow it. This is the most common reason applications suddenly cannot find their neighbours. A later chapter covers the fix.
Egress and Third-Party Services
Modern applications depend on many outside services: payment providers, email senders, analytics tools, and cloud storage. Each is a possible egress destination, and each needs a decision. For important ones with stable addresses, list them explicitly. For those with changing addresses, consider routing through an egress gateway that can apply name-based rules and records every call.
Keeping a written inventory of external dependencies helps enormously. When a new dependency is added, the inventory prompts a review of the egress rules. When a dependency is retired, the inventory prompts removal of the rule, preventing old openings from lingering for years.
9Peers: Pods, Namespaces, and Address Ranges
A rule identifies the other end of a connection in one of three ways.
Pod Selector
Chooses pods by their labels, within the same namespace as the policy unless combined with a namespace selector.
Namespace Selector
Chooses whole namespaces by their labels, so every pod in matching namespaces qualifies.
IP Block
Chooses a range of network addresses, with optional exceptions, used mainly for things outside the cluster.
Pod Selectors
A pod selector is the everyday tool. It says that pods carrying certain labels are the allowed peers. When used alone in a rule, it refers only to pods in the same namespace as the policy. This is why policies naturally stay local by default.
Namespace Selectors
A namespace selector chooses namespaces by their labels, not by their names. This surprises beginners. Namespaces must carry labels for the selector to find them. Modern clusters automatically label each namespace with its own name, which makes selecting by name possible, but you may also add your own labels such as environment equals production.
IP Blocks
An IP block names a range of addresses and may carve out exceptions. It suits traffic to and from things outside the cluster, such as a partner service or an office network. It is not the right tool for pods inside the cluster, because pod addresses change constantly. Also be aware that some network setups change the apparent source address of traffic, which can make IP blocks behave unexpectedly for external sources.
You can identify guests in three ways. By badge, which is a pod selector. By department, which is a namespace selector. Or by the street they come from, which is an IP block. Badges and departments work best for people inside the company, and the street works best for outsiders.
Use pod and namespace selectors for anything inside the cluster, and IP blocks only for external addresses that rarely change.
Labels on Namespaces in Practice
Because namespace selectors depend on namespace labels, your organization needs a plan for labelling namespaces. Some clusters add a label with the namespace’s own name automatically, which is convenient. Beyond that, useful labels include the owning team, the environment, and the sensitivity level. With such labels, a single policy can admit all namespaces of one team, or refuse all namespaces marked as untrusted.
Protect the ability to change namespace labels. Since policies trust these labels, anyone who can add a label to their own namespace could gain access that the label grants. Treat label changes on namespaces as security-relevant, and restrict them with access control.
10The And-Or Trap: Combining Selectors
A tiny difference in how selectors are written changes a policy from safe to wide open.
Two Shapes That Look Almost Alike
Within one rule, you can list several peers. If a namespace selector and a pod selector appear together as two parts of the same peer, they combine with and: only pods that match the pod selector inside the namespaces that match the namespace selector qualify. If they appear as two separate peers in the list, they combine with or: any pod matching the pod selector in the policy’s own namespace, plus every pod in the matching namespaces, qualifies.
The difference in the written form is only a small indentation, one extra dash, yet the effect is very large. The and form is narrow and precise. The or form is broad and often not what the author intended, since it admits every pod in the chosen namespaces.
| Form | Meaning | Who Qualifies |
|---|---|---|
| Namespace selector and pod selector in one peer | Both must match | Only labelled pods inside matching namespaces |
| Namespace selector and pod selector as separate peers | Either may match | All pods in matching namespaces, plus labelled pods in the policy’s namespace |
flowchart TD
subgraph AND[AND form: one peer with both selectors]
A1[Pod must have label] --- A2[and live in a matching namespace]
A2 --> A3[Narrow: only monitoring pods in the monitoring namespace]
end
subgraph OR[OR form: two separate peers]
B1[Any pod with the label in the policy namespace] --- B2[or any pod in a matching namespace]
B2 --> B3[Wide: every pod in the monitoring namespace is allowed]
end
A party invitation that reads people from the marketing department who wear a blue badge admits only blue-badge marketers. A card that reads people from marketing, or anyone with a blue badge admits all of marketing and all blue-badge wearers from anywhere. One little word changes the size of the crowd.
This is the most common way Network Policies end up wider than intended. When reviewing, read the structure of every peer list slowly, and test that pods which should be refused really are.
A Habit for Reading Peer Lists
A reliable habit for reading any peer list is to count the dashes, mentally, at the start of each peer entry. Each dash begins a new peer. Selectors that share one dash belong together and must both match. Selectors under different dashes stand alone, and either one is enough. Reading this way, slowly and aloud, catches the misplaced dash that changes the meaning.
When you find a rule that is hard to read, rewrite it as two clearer rules rather than keeping a clever one. Clarity is more valuable than compactness in security configuration, and a rule that a colleague can understand is a rule that a colleague can review.
11Ports and Protocols
Ports narrow a rule from allowing anything to allowing exactly one kind of conversation.
Port Numbers and Names
A port entry gives a protocol, most often TCP, and a port number. It may also give a named port, which refers to a port name defined on the pod, so that the policy keeps working if the number changes. Ranges of ports are also supported in newer versions, which helps for applications that use a block of consecutive ports.
Protocols Supported
Network Policies handle TCP, UDP, and in supporting plugins, SCTP. If no protocol is written, TCP is assumed, which surprises people who expect name lookups over UDP to work under a default rule. Traffic types that are not connection-based in the usual way, such as some kinds of ping messages, are handled differently by different plugins, and the standard does not define their behaviour.
TCP
The default for most applications: web servers, databases, and message queues.
UDP
Used by name lookups and some streaming or gaming traffic. Must be named explicitly.
SCTP
Used in telecommunications. Supported only by some plugins.
An office building has one front entrance but many numbered offices. Letting a visitor into the building is different from letting them into office 42. Ports are the office numbers, and protocols are the ways visitors arrive, on foot or by lift. Precise rules name both.
Where possible, give container ports names and refer to those names in policies. If a team later changes the number, the policy still matches, and you avoid a silent breakage.
Policies match the port on the pod itself, not the port shown by a service in front of it. If a service listens on 80 and forwards to a pod on 8080, the policy must allow 8080.
Choosing Ports Carefully for Shared Pods
Some pods serve more than one purpose, listening on one port for customers and on another for metrics or administration. Network Policies let you treat these differently, exposing the customer port to the ingress controller and the metrics port to the monitoring system, while leaving the administration port closed to everyone. This separation is one of the cheapest ways to reduce the attack surface of an application.
If an application exposes an administration port that nobody uses, closing it with policy is a sensible precaution. Closing it in the application itself is even better, but policy gives you a safety net when the application cannot be changed quickly.
12The Additive Model: Rules Only Add
Network Policies never conflict, because they can only allow, and allowances simply add together.
The Union of Everything
If several policies select the same pod, the pod may do everything that any of them allows. Policies are combined as a union. There is no order of evaluation, no priority, and no way for one policy to cancel another. This eliminates a whole category of confusing problems that plague firewalls with ordered rules and explicit denies.
flowchart LR
P1[Policy A allows API to database] --> U[Union of all allowances]
P2[Policy B allows monitoring to database metrics port] --> U
P3[Policy C allows backup job to database] --> U
U --> R{Connection matches any allowance?}
R -- Yes --> OK[Allowed]
R -- No --> NO[Dropped]
What This Means in Practice
Because policies add up, you can write small, separate policies for separate needs and rely on their sum. One policy for the API, one for monitoring, one for backups. It also means that you can never make a pod safer by adding another policy on top of a generous one. To tighten access, you must remove or narrow the generous policy.
A club’s door has several separate guest lists: members, sponsors’ guests, and staff. A person may enter if their name is on any of the lists. Adding a new list can only admit more people. To keep someone out, you remove their name from every list.
A forgotten broad policy, such as allow everything from everywhere, silently cancels the effect of all your careful narrow policies for the pods it selects. When protection seems not to work, look for a wide policy that adds too much.
Connections Are Two-Way, Rules Are Not
When a connection is allowed, the replies flowing back along the same connection are also allowed automatically. You do not need to write a rule for the return traffic. However, both ends can enforce policy: the sender’s egress rules and the receiver’s ingress rules must both allow the connection if both pods are isolated. A connection needs permission at both ends to succeed.
Thinking in Terms of Paths, Not Pods
A helpful way to design policies is to think in paths rather than in individual pods. A path is a single allowed conversation: this tier may call that tier on this port. Writing down the paths of an application yields a short list, usually ten or twenty items, that captures the whole design. Each path becomes one or two policies, one for the sender and one for the receiver.
Thinking in paths also makes reviews meaningful. A reviewer can look at the list and ask whether each path is truly necessary, whether any direct path could be removed by going through an intermediate tier, and whether any path crosses a sensitive boundary. These are questions of design, not just of syntax.
13Default Deny: The Foundation of Good Security
The safest starting point is a namespace where everything is closed, and only needed paths are opened.
What Default Deny Means
A default deny policy selects every pod in a namespace, using an empty pod selector, and lists no allowed sources or destinations. Because selected pods are isolated and nothing is allowed, every connection to and from those pods is refused. From that closed state, you add small policies that open only the paths the applications need.
Deny All Ingress
No pod in the namespace accepts incoming connections unless another policy allows it.
Deny All Egress
No pod in the namespace may open outgoing connections unless another policy allows it.
Deny Both
The strictest starting point, closing both directions for every pod in the namespace.
Allow All
An explicit, deliberate policy that opens everything in a direction, used only for special cases and to document intent.
A well-run laboratory keeps every door locked by default and gives each person keys to only the rooms they need. Doors do not start open with a plan to lock them later. A default deny policy locks every door first.
Rolling It Out Safely
Map the traffic
Learn which pods talk to which, using diagrams, service definitions, and traffic observation tools.
Write the allow policies first
Create policies for each needed path while the namespace is still open, so nothing changes yet.
Apply default deny in a test environment
Confirm that applications still work and that unwanted paths are refused.
Apply default deny in production
Do it at a quiet time with the team watching, and be ready to remove it quickly if something breaks.
Applying default deny to a busy namespace before writing the allow policies will break the applications instantly. Always prepare the openings first.
Keeping Default Deny Healthy Over Time
Default deny is not a one-time act. As applications change, new connections are needed, and old ones disappear. Teams that fail to keep policies up to date face two problems: outages when a new dependency is blocked, and stale openings that nobody removes. A regular review, ideally connected to the release process, keeps the policies aligned with reality.
A helpful rule is that any change to an application’s connections must include a matching change to its policies, in the same change request. Reviewers then see both sides together, and the policies never lag behind the code.
14Allowing Name Lookups
Almost every application needs to translate names into addresses, and a strict egress policy must leave that door open.
Why DNS Matters
Applications rarely use numeric addresses. They use names such as the payments service, and the cluster’s name lookup service, called DNS, turns them into addresses. This service runs as pods in the system namespace. When you restrict egress, a pod can no longer reach those DNS pods, and every name lookup fails. Applications then report that they cannot find their databases, even though the databases are running perfectly.
The Standard Fix
The fix is a small egress policy that allows pods to connect to the DNS pods, using both UDP and TCP on port 53. Many teams apply it to every namespace as part of the default setup, together with default deny. Selecting the DNS pods by namespace label and pod label keeps the rule narrow.
sequenceDiagram
participant W as Web pod
participant D as DNS pods
participant A as API pod
W->>D: Where is the API service? (port 53)
D-->>W: Here is its address
W->>A: Connect to the API (allowed by policy)
A-->>W: Reply
If you lock the office phone directory in a cupboard, nobody can find anyone’s extension, and everyone believes their colleagues have vanished. The colleagues are fine. The directory is simply out of reach. DNS is the directory, and it needs a rule of its own.
If pods suddenly report that hosts cannot be resolved after you add egress restrictions, DNS is the first suspect. Test a name lookup from inside the pod before searching elsewhere.
Resist the temptation to allow all egress to the system namespace. Allow only the DNS pods and only port 53, so that other system components stay out of reach.
Local DNS Caches and Special Cases
Some clusters run a local name cache on every node to speed up lookups. Pods then talk to the cache rather than the central DNS pods, and the cache uses its own addresses. If your policy allows only the central DNS pods, lookups may still fail. Learn how name resolution works in your cluster before writing the rule, and test lookups from a restricted pod.
Also remember that some applications use their own resolvers or connect to external name servers. These need to be considered in the egress design, either allowed explicitly or, better, replaced by the cluster’s own lookup service.
15Isolating Namespaces From Each Other
A common goal is to make each namespace a private neighbourhood, open inside and closed to visitors.
The Same-Namespace Pattern
To let pods in a namespace talk to each other but not to other namespaces, write an ingress policy that selects all pods and allows connections only from all pods in the same namespace. Combined with default deny for anything else, this turns each namespace into a sealed area. Applications inside work as before, and outsiders are refused.
Opening Controlled Doors
Namespaces usually need a few controlled openings. The monitoring system in its own namespace must scrape metrics. The ingress controller in another namespace must forward user traffic. A shared logging service must receive logs. Each of these gets its own narrow policy naming the specific namespace, pod labels, and ports.
| Need | Policy Direction | Peer | Port |
|---|---|---|---|
| Pods talk within the namespace | Ingress | All pods in the same namespace | As required by the application |
| Monitoring scrapes metrics | Ingress | Monitoring pods in the monitoring namespace | Metrics port only |
| Public traffic arrives | Ingress | Ingress controller pods | Web port only |
| Applications resolve names | Egress | DNS pods in the system namespace | Port 53 |
| Applications log centrally | Egress | Logging service namespace | Logging port only |
In a gated community, residents move freely between their own homes, while the gate lets in only the mail carrier, the utility engineers, and expected guests. Namespace isolation builds the gate, and the narrow policies are the visitors’ list.
Apply meaningful labels to namespaces, such as team and environment, so that policies can select groups of namespaces easily and stay valid as new namespaces appear.
Shared Services Across Namespaces
Real clusters contain shared services, such as logging, tracing, certificate management, and message brokers, used by many namespaces. Each such service needs both an ingress policy on its own side, allowing the calling namespaces, and egress policies on the caller side. Using a label on the calling namespaces, such as a label that marks them as consumers, lets a single policy on the shared service admit them all without listing each one.
This pattern scales well. When a new team joins, giving its namespace the consumer label is enough to grant access, and removing the label revokes it at once. The policies themselves do not need to change.
16A Three-Tier Application, Step by Step
Walking through a typical shop application shows how the pieces fit together.
The Setting
An online shop has three tiers. A web tier serves pages to customers. An API tier holds the business logic. A database tier stores orders. Customers should reach only the web tier. The web tier should reach only the API tier. The API tier should reach only the database. Nothing else should be connected.
flowchart LR
C[Customers] -->|443| I[Ingress controller]
I -->|8080| W[Web pods]
W -->|9090| A[API pods]
A -->|5432| D[Database pods]
M[Monitoring] -.metrics only.-> W
M -.metrics only.-> A
The Policies You Would Write
Default deny for both directions
Close everything in the shop namespace so that the starting point is safe.
Allow name lookups
Let all pods reach the DNS pods on port 53.
Allow the ingress controller to the web tier
Ingress for web pods from the controller pods, on the web port only.
Allow web to API
Egress from web pods to API pods, and ingress on the API pods from web pods, on the API port.
Allow API to database
Egress from API pods to database pods, and ingress on the database pods from API pods, on the database port.
Allow monitoring
Ingress on web and API pods from the monitoring namespace, on metrics ports only.
A bank has a public lobby, a staff area, and a vault. Customers reach the lobby. Tellers reach the staff area. Only a few managers reach the vault. Each area has its own door and its own guest list, and passing through one door does not open the next. The three tiers work the same way.
When both sides are isolated, remember to write the egress rule on the sender and the ingress rule on the receiver. Forgetting one end is the most frequent reason a new path does not work.
Adjusting the Example for Your Own Application
The three-tier example is only a starting point. Real applications add caches, queues, search engines, and background workers, each with its own paths. The method stays the same: list the components, draw the arrows that must exist, and turn each arrow into policies on both ends. Add default deny and DNS to every namespace, and the design is complete.
When in doubt, run the application in a test namespace with default deny on, and watch what fails. Each failure points to a missing path. Add the path deliberately, after asking whether it is really needed, and continue until the application works and no unexpected path remains.
Extending the Example to Background Workers
Most real applications include background workers that process queues, send emails, or generate reports. These workers usually need paths to the database and to the queue, but no path from the public internet. In policy terms, they receive no ingress at all and have carefully limited egress. Giving workers their own labels and their own small policies keeps them from inheriting the openings meant for web pods.
Workers are also a common target for supply-chain problems, since they often run large amounts of third-party code. Tight egress rules on workers are therefore especially valuable, because they stop harmful code from contacting outside servers even if the package is compromised.
17Traffic From Outside the Cluster
Customers, load balancers, and ingress controllers reach your pods through paths that need careful thought.
How Outside Traffic Arrives
Users on the internet rarely connect straight to your pods. They reach a load balancer, which forwards to an ingress controller or a service, which in turn forwards to pods. By the time a connection reaches your web pod, its apparent source may be the ingress controller, a node address, or the original client address, depending on how the cluster and the cloud are set up. The source that the policy sees determines what your rule must allow.
Three Common Arrangements
Ingress Controller in the Cluster
Traffic reaches controller pods, which then connect to your web pods. Your policy allows connections from the controller pods, selected by namespace and pod label. This is the cleanest arrangement.
Load Balancer Straight to Pods
The cloud load balancer sends traffic to nodes or to pods directly. The apparent source may be a node address or a load balancer address range, which an IP block may need to allow.
Node Port Access
Traffic enters through a port on each node. Depending on the plugin, the source can be the node itself, and policies on the pod may treat node traffic specially.
When a parcel arrives at your flat, the doorman does not see who posted it. He sees the courier. Your visitors list must therefore name the courier company, not the original sender. Policies see the last hop, so name the last hop.
Because the apparent source depends on your platform, always test a policy with a real request from outside the cluster. A policy that looks correct on paper can block genuine customers or admit too many.
Do not rely on Network Policies alone at the edge. Combine them with cloud firewalls, security groups, and web application firewalls, each covering what the others cannot.
Health of the Edge Path
The path from the internet to a pod passes through several components, and any of them can fail or be misconfigured. When customers report that a site is unreachable after a policy change, it is tempting to blame the policy at once. A calmer approach checks each hop in turn: the load balancer, the ingress controller, the service, and finally the pod. Policy is only one of those hops, but it is the newest change, so it deserves suspicion first.
Keeping a simple diagram of the edge path and its policies on hand makes such investigations much quicker. Each hop in the diagram has an owner, a rule, and a test, so the team can rule out hops one by one.
18Controlling Traffic to the Outside World
Egress to the internet and to external services is where data theft and callbacks happen, so it deserves its own design.
Allow Lists of Addresses
Standard Network Policies can name external destinations only by address ranges, using IP blocks. This works well for a small number of stable destinations, such as a payment provider whose addresses are published, or a corporate network. It works poorly for services whose addresses change often, such as content delivery networks and many software-as-a-service products, because you would need to keep the ranges up to date.
Blocking the Dangerous Places
Even where you cannot list every allowed destination, you can block dangerous ones. A common example is the metadata service that cloud providers expose to virtual machines at a special internal address. If a pod can reach it, an attacker may steal credentials belonging to the underlying machine. An egress rule that allows general outbound traffic but excludes that address closes this well-known hole.
Allow Specific Ranges
Permit only the published address ranges of the few services your pods must call.
Exclude Sensitive Addresses
Allow outbound traffic but exclude the cloud metadata address and internal management networks.
Use an Egress Gateway
Send all outside traffic through a controlled proxy that applies name-based rules and logging.
Use Plugin Extensions
Some plugins add name-based egress rules, letting you allow a domain name instead of address ranges.
A company may let staff make outside phone calls but block premium-rate numbers and route international calls through the switchboard. Egress policy works in the same way: broad permission with sharp exceptions, or narrow permission with a supervised gateway.
If you take only one egress step, block pods from reaching the cloud metadata address unless they truly need it. It is a small change with a large security payoff.
Egress Gateways in Everyday Terms
An egress gateway is a small set of pods through which all outside traffic must flow. Policies then allow application pods to talk only to the gateway, and the gateway alone may talk to the internet. This concentrates control into one place: the gateway can enforce name-based rules, log every outside call, and present a single stable address to external partners who want to allow your traffic on their side.
The trade-off is added complexity and a new component that must be highly available. For small clusters, address-based rules may be enough. For regulated or high-risk environments, the gateway is often worth the effort.
19Testing and Verifying Your Policies
A policy you have not tested is only a hope, so verification is part of the job.
Test Both Directions of Result
Testing has two halves. First confirm that the connections you intend to allow really work. Second, and more important for security, confirm that the connections you intend to block really fail. Many teams test only the first half, see that the application works, and assume all is well, while unwanted paths remain wide open.
Simple Test Methods
The simplest method is to start a temporary pod with a small networking tool, place it in the namespace and with the labels of the pod you want to test as, and attempt connections to the target. A successful connection means allowed and a timeout means blocked. Because blocked packets are dropped silently, a blocked connection typically hangs until it times out rather than being refused at once. That hanging behaviour is itself a hint that a policy is at work.
Write a test list
List source, destination, and port for every connection that must work and every one that must fail.
Run the allowed tests
Confirm each intended path succeeds.
Run the blocked tests
Confirm that connections from wrong pods, wrong namespaces, and wrong ports time out.
Repeat after every change
Automate the list in your pipeline so that any change that widens access is caught immediately.
After fitting a new lock, you do not only check that your key turns. You also check that the door stays shut when someone pushes it and that a spare key does not work. Testing blocked cases is the pushing.
Before trusting any results, run a simple test with a deny-all policy and confirm that a connection really fails. That single check proves that your network plugin enforces policies at all.
Policy Testing Tools and Simulation
Several tools help you check policies before they reach production. Some read policy files and answer questions such as which pods can reach this pod, drawing a map of allowed paths. Others simulate connections and report which policy allowed or blocked them. Using such tools in a pipeline catches mistakes when they are cheap to fix.
Even a simple review checklist helps: does every namespace have a default deny, does every workload with egress restrictions have DNS allowed, do any policies allow all sources, and do any peer lists combine selectors in the wide form. Answering these four questions catches a large share of real-world errors.
20Troubleshooting Blocked Connections
When something stops working after a policy change, a calm, ordered search finds the cause quickly.
flowchart TD
S[Connection fails or hangs] --> N{Is it a name lookup problem?}
N -- Yes --> DNS[Allow egress to DNS pods on port 53]
N -- No --> I{Does a policy select the destination pod for ingress?}
I -- Yes --> IA{Does an ingress rule allow this source and port?}
IA -- No --> FIXI[Add or correct the ingress rule]
IA -- Yes --> E
I -- No --> E{Does a policy select the source pod for egress?}
E -- Yes --> EA{Does an egress rule allow this destination and port?}
EA -- No --> FIXE[Add or correct the egress rule]
EA -- Yes --> L[Check labels, namespace labels, and service ports]
E -- No --> L
The Usual Suspects
Blocked DNS
Egress was restricted without allowing name lookups.
One End Only
The sender’s egress rule exists but the receiver’s ingress rule is missing, or the reverse.
Label Mismatch
A pod label was changed or mistyped, so the selector no longer matches.
Namespace Labels Missing
A namespace selector refers to a label the namespace does not carry.
Wrong Port
The policy allows the service port instead of the pod’s actual port.
Wrong Protocol
A UDP need was left unwritten, so only TCP is allowed.
When a delivery does not arrive, you check the address on the parcel, whether the sender actually posted it, whether the doorman had it on the list, and whether the building has the right street number. Each check corresponds to one of the causes above.
Begin every investigation by listing the policies in both namespaces involved, and note which ones select the source and destination pods. Most puzzles solve themselves once you see the whole set.
Recording What You Learn
Every troubleshooting session teaches something about your cluster. Recording the cause and the fix in a shared page turns individual experience into team knowledge. Over time, the page becomes a guide to your own environment: which applications need which special paths, which plugin quirks matter, and which mistakes recur. New team members learn faster, and repeated outages become rarer.
Include the symptom in the record, in the words people actually use, such as cannot resolve host or connection times out. Future searchers will type those same words, and finding the page quickly is half of the solution.
21Observing and Auditing Network Traffic
To keep policies correct over time, you need to see what traffic actually flows and what gets dropped.
Why Standard Kubernetes Shows Little
The basic Network Policy feature has no logging. Dropped packets vanish without a trace, and Kubernetes offers no built-in report of denied connections. Beginners find this frustrating, because a blocked connection produces a timeout with no explanation. Visibility must come from the network plugin or from separate tools.
Sources of Visibility
Plugin Flow Logs
Many advanced plugins record allowed and denied connections and can show them in dashboards.
Traffic Observation Tools
Tools that watch the network and draw a map of which workloads talk to which.
Service Mesh Telemetry
Where a mesh is used, it reports connections between services with rich detail.
Node Level Logs
Kernel filtering logs on nodes can reveal drops, though they are harder to interpret.
Using Visibility to Design Policies
Traffic maps are especially valuable when you are protecting an existing application whose connections nobody fully remembers. Observe real traffic for a period, draw the map, and turn each observed legitimate flow into a policy. Then review the flows that surprise you: they are often forgotten dependencies or, occasionally, signs of something suspicious.
Before installing door locks in a large building, a sensible manager first watches who walks where for a few weeks. Drawing the real paths prevents locking doors that the cleaners, engineers, and mail carriers use every day.
Alert when a new policy is created or an existing one is edited, especially any policy that allows all sources. Access changes to the network deserve the same attention as changes to user permissions.
Reading Traffic Maps With a Security Eye
A traffic map is more than a design aid. Read it as an intruder would. Which workloads have paths to sensitive ones? Which paths seem unnecessary? Which workloads talk to the outside world, and to where? A map often reveals a tool that can reach far more than its purpose requires, giving you an obvious next policy to write.
Comparing maps over time is also useful. A new path that appears without a matching change request deserves investigation. It may be an honest new feature, a forgotten test, or occasionally an intrusion. Either way, you want to know the same day.
22Going Beyond the Standard: Extended Policies
The standard Network Policy is deliberately simple, so many network plugins offer richer versions for demanding needs.
What the Standard Cannot Do
The standard object has several limits. It has no way to deny explicitly. It cannot set priorities between rules. It cannot apply a single rule across all namespaces at once, because every policy lives in one namespace. It cannot allow or deny by domain name, and it offers no logging. It works only at the connection level and cannot examine the contents of requests.
What Extensions Add
| Capability | Standard Policy | Typical Plugin Extension |
|---|---|---|
| Explicit deny rules | Not available | Available, with ordering or priority |
| Cluster-wide rules | One namespace per policy | Cluster-scoped policies for baseline rules |
| Domain name rules | Not available | Allow or deny by name |
| Logging of decisions | Not available | Flow logs for allowed and denied traffic |
| Request-level rules | Not available | Rules on web request paths and methods in some plugins and meshes |
| Identity-based rules | By labels only | By workload identity and encryption in some meshes |
A basic padlock is enough for a garden shed. A bank needs a vault door with timers, cameras, and logs. Standard policies are the padlock, and plugin extensions are the vault features. Choose according to what you protect.
Extended policies are specific to a plugin. Adopting them ties your security design to that plugin. Where the standard object is enough, prefer it for portability, and use extensions only for needs that truly require them.
Network Policies pair naturally with service meshes that encrypt traffic and verify identity. The policy decides who may connect, and the mesh proves who is really connecting.
Deciding Whether You Need Extensions
Before adopting extended policies, list the needs that standard policies cannot meet. If your list is short and consists of items like logging, then a plugin with flow logs may be enough while you stay with standard policies for rules. If your list includes explicit deny, cluster-wide baselines, and name-based egress, extended policies are likely worth it.
Whichever way you decide, keep the design understandable. Extra features tempt teams to build elaborate layers of rules with priorities and exceptions. Complexity is the enemy of security, because nobody can verify what they cannot understand. Prefer the simplest design that meets the requirements.
23Advantages and Trade-offs of Network Policies
Network Policies deliver large security gains, but they ask for care and discipline in return.
Advantages
- Limit lateral movement, so one compromised pod cannot easily reach the rest
- Use labels, so rules follow pods as they are replaced and scaled
- Written as data in version control, so they can be reviewed and audited
- Additive and order-free, so policies never conflict
- Part of standard Kubernetes, with wide support in network plugins
- Help meet compliance requirements for network segmentation
Disadvantages / Trade-offs
- Enforced only if the network plugin supports them, with a risk of false confidence
- No logging or explicit deny in the standard object
- Rules are limited to addresses, ports, and labels, not content or identity
- Mistakes such as blocked name lookups can cause sudden outages
- Large numbers of policies become hard to understand without good tooling
Weighing the Balance
The trade-offs are real but manageable. The risk of outages is handled by careful rollout, testing, and small policies. The lack of visibility is handled by plugin features and traffic maps. The limit to addresses and ports is handled by pairing policies with identity-based tools. The benefit, a cluster where a single mistake cannot become a disaster, is worth the effort for nearly every production environment.
Locks on doors slow the residents down slightly and occasionally trap someone outside. Nobody concludes that buildings should have no locks. They learn to carry keys, keep spares, and test the doors. Network Policies ask for the same habits.
When Network Policies Are Most Valuable
Network Policies pay off most in clusters that share workloads between teams, handle sensitive data, or face the public internet. In such environments, the cost of one lateral movement can be enormous, and the effort of writing policies is small by comparison. In a tiny personal cluster running a hobby project, the benefit is smaller, though the habits learned there transfer directly to serious environments.
A useful test is to imagine that any single pod in your cluster has just been taken over by a stranger. Ask what that stranger could reach in the next ten minutes. If the honest answer is everything, policies are overdue. If the answer is a short, acceptable list, your segmentation is working.
24Best Practices and Common Mistakes
A short list of habits separates clusters that are truly segmented from clusters that only appear to be.
Habits Worth Building
Start With Default Deny
Close each namespace first, then open only what is needed.
Control Egress Too
Protect exits as carefully as entrances, and always allow DNS narrowly.
Label Consistently
Use a shared scheme for application, tier, and environment labels on pods and namespaces.
Keep Policies Small
One purpose per policy, with a clear name that states the path it opens.
Test Blocked Paths
Automate tests that prove forbidden connections fail.
Store in Version Control
Review changes like code, and compare the live cluster to the files regularly.
Problem
The team writes policies on a cluster whose network plugin does not enforce them.
Why It’s Harmful
Everything looks protected, audits pass on paper, and nothing is actually blocked. An attacker moves freely while the team feels safe.
Correct Approach
Choose a plugin that enforces policies, and prove it with a simple deny test before relying on any policy.
Problem
Only ingress is controlled, and egress is left fully open everywhere.
Why It’s Harmful
A captured pod can still send stolen data anywhere and can contact outside command servers.
Correct Approach
Apply default deny to egress as well, then allow DNS and the specific destinations each workload needs.
Problem
To fix an outage quickly, someone adds an allow-all policy to a namespace and forgets it.
Why It’s Harmful
Because policies add up, this single policy cancels the effect of every careful rule for the pods it selects.
Correct Approach
Diagnose the missing path, add the narrow rule that fixes it, and review any broad policy immediately after an incident.
Problem
Peer lists are written with a namespace selector and a pod selector as separate items, when the author meant both to apply together.
Why It’s Harmful
The rule admits every pod in the chosen namespaces, not just the intended ones, widening access far beyond the plan.
Correct Approach
Write the two selectors inside the same peer when both must match, and test that unintended pods are refused.
Relying on names of namespaces without checking that the namespaces carry the labels your selectors expect. A selector that matches nothing quietly allows nothing, and the outage looks mysterious.
Naming and Documenting Policies
Clear names make policies self-explanatory. A name such as allow-api-to-database says at once what the policy does, while a name such as policy-7 says nothing. Adding a short description in an annotation, stating who requested the path and why, saves hours during reviews. When someone asks why a path exists, the answer is right there.
Consistent names also help searching and automation. Scripts can find all default deny policies, all DNS policies, and all policies that touch the database, simply by looking at the names and labels. This turns a pile of objects into an organized collection.
25Real-World Examples and an Adoption Roadmap
Network Policies appear in every serious cluster, in patterns that are easy to recognize.
Situations Where Policies Prove Their Worth
The Compromised Web Pod
An attacker exploits a flaw in a public web application and gains a shell inside a web pod. Because policies allow the pod to reach only the API tier, the attacker cannot scan the database, the secret store, or other teams’ services. The intrusion is contained and noticed.
The Shared Cluster
A company runs many teams in one cluster. Each namespace is sealed by default deny, with narrow openings for shared services. A bug in one team’s test workload cannot reach another team’s production data.
The Regulated Payment Workload
A payments service must be separated from the rest of the environment for compliance. Policies allow only the checkout service to connect in, and only one provider to be contacted out. Auditors can read the policies as evidence of segmentation.
The Data Leak That Did Not Happen
A malicious package inside a batch job tries to send customer records to an unknown server. Egress rules permit only the storage service, so the outbound connection times out, and the alert on failed connections draws attention to the job.
A Gentle Adoption Roadmap
Confirm enforcement
Verify that your network plugin supports policies and that a test deny really blocks traffic.
Fix labels
Agree on a labelling scheme for pods and namespaces.
Map traffic
Observe real flows for each application and draw the map.
Start with one namespace
Apply default deny, DNS, and the mapped paths to a low-risk namespace first.
Roll out gradually
Extend to other namespaces, sensitive ones first, using the same templates.
Automate and review
Test in pipelines, alert on policy changes, and review policies on a schedule.
Keeping the Momentum After the Rollout
Once the first namespaces are protected, the hardest part is often keeping the effort alive. New services appear, teams change, and shortcuts creep in. Build the protections into the normal path of work: templates that give every new namespace a default deny and a DNS policy, checks in the pipeline that reject policies allowing all sources, and a short review step for any change to network rules.
Celebrate small wins as well. Each time a policy blocks something unexpected and the alert draws attention to it, share the story with the team. Stories of real incidents that were contained do more to sustain good habits than any rule document, because they show that the effort truly matters.
26Frequently Asked Questions
Short answers to the questions beginners ask most often about Network Policies.
No. By default, every pod can reach every other pod across all namespaces. Isolation begins only when a Network Policy selects a pod.
The most likely reason is that your network plugin does not enforce Network Policies. Kubernetes stores the object without complaint. Check the plugin’s documentation and run a deny test.
Not with the standard object. It only allows. You achieve a denial by isolating pods and not allowing the traffic. Some plugins provide extended policies with explicit deny.
Their allowances are combined. The pod may do anything that at least one policy allows. There is no ordering and no conflict.
Most often because name lookups were blocked. Allow egress to the DNS pods on port 53, using both UDP and TCP.
No. Replies to an allowed connection are permitted automatically. You only need to allow the connection in the direction it is opened.
No. A policy selects pods only in its own namespace. It can, however, allow peers from other namespaces by using a namespace selector.
If the namespace selector and pod selector are in the same peer, both must match. If they are separate peers, either may match, which is much broader.
No. Pod addresses change constantly. Use pod and namespace selectors for in-cluster traffic, and reserve IP blocks for stable external ranges.
No. They control which connections may be opened, not whether the data is encrypted. Use encryption in the application or a service mesh for that purpose.
The standard feature has no logging. Use flow logs or observation features from your network plugin, or a separate traffic monitoring tool.
It is an excellent foundation, but you must add narrow policies to open the paths your applications need, including name lookups. Pair it with testing, monitoring, and other security layers.
Where to Learn More Safely
The best way to learn Network Policies is to practise in a scratch cluster. Create a namespace with a few simple pods, try connections, apply default deny, and watch them fail. Open one path at a time and watch it succeed. Deliberately make the classic mistakes, such as blocking DNS and misplacing a dash, so that you recognize them when they appear in real work.
Alongside practice, read the documentation of your own network plugin, because its behaviour details matter. Small differences in how node traffic, external sources, and unusual protocols are treated can change results, and only your own tests can settle them.
27Summary and Key Takeaways
Kubernetes starts with a flat, open network in which every pod can reach every other pod. Network Policies fix this by describing, with labels, exactly which connections are allowed. Pods selected by a policy become isolated in the chosen directions, and only the allowed paths remain. Because policies only add allowances, they never conflict, and a good design starts from default deny and opens narrow, well-tested paths.
Success depends on a network plugin that enforces the rules, on careful handling of name lookups and of both ends of every connection, and on testing that blocked paths really fail. With those habits, Network Policies keep a single compromised pod from becoming a compromised cluster.
Key Takeaways
- Open by default — without policies, every pod can talk to every other pod, across namespaces.
- Enforcement needs a plugin — a policy is only a description, so confirm that your network plugin enforces it and test it.
- Allow lists only — policies allow traffic, and anything not allowed is dropped for the pods they select.
- Start with default deny — close each namespace first, then open narrow paths for each real need, including DNS.
- Control both directions — ingress limits who can reach a pod, and egress limits where a compromised pod can send data.
- Mind the selectors — the difference between one peer and two peers changes and into or, and widens access.
- Test, observe, review — prove that blocked paths fail, watch traffic, and keep policies in version control.