internal pod so it can only reach the payroll and mysql pods.
Note: the examples below use the k alias for kubectl. If you don’t have that alias, either set it (alias k=kubectl) or replace k with kubectl in the commands.
By default, pods allow all ingress and egress traffic. When a NetworkPolicy selects a pod for a particular policy type (
Ingress or Egress), traffic in that direction becomes restricted: only the explicitly allowed traffic is permitted.1) Inspect the cluster: pods and services
Start by listing pods in thedefault namespace:
2) Identify NetworkPolicies in the environment
List NetworkPolicies in the namespace:payroll-policy to see its rules:
- The policy selects the
payrollpod (name=payroll). - It allows ingress only to TCP port
8080and only from pods labeledname=internal. - There are no egress rules defined for
payroll, so egress from thepayrollpod is unrestricted. - Because
Policy Typesincludes onlyIngress, ingress to thepayrollpod is restricted to the defined sources; other ingress is denied.
3) What traffic is allowed / blocked by payroll-policy?
Summary:
So, for example:
internal->payroll:8080is allowed.external->payroll:8080is blocked.payroll-> anywhere is allowed.
4) Connectivity verification (UI / application tests)
Using the apps’ web UI or built-in connectivity tests:- From the internal-facing application: connecting to
payroll:8080succeeds (allowed). - From the external-facing application: connecting to
payroll:8080times out / fails (blocked).
internal->external:8080succeeds (no policy prevents that).internal-> database (mysql:3306) currently succeeds (no egress policy yet).
payroll-policy.
Caution: when you add
policyTypes: ["Ingress"] or ["Egress"] without specifying the corresponding rules, you will restrict that traffic direction. For example, adding Ingress without any ingress rules will deny all ingress to the selected pods.5) Task: Create a policy to restrict egress from internal
Goal: create a NetworkPolicy named internal-policy that selects the internal pod and allows egress only to:
payrollpod on TCP port8080mysqlpod on TCP port3306
internal-policy.yaml with the following manifest:
podSelector.matchLabels.name: internaltargets theinternalpod(s).policyTypes: ["Egress"]restricts only egress; ingress behavior remains unchanged.- The
egressrules permit only the two specified destinations. When a pod is selected by a NetworkPolicy that definesEgress, all other egress traffic is denied unless another policy allows it.
6) Apply the policy and verify
Apply the manifest:- The
internalpod should now only be able to reach:payroll:8080(TCP)mysql:3306(TCP)
- Attempts from
internalto reach any other service or external host should be blocked unless another NetworkPolicy explicitly allows them. - The existing
payroll-policystill restricts ingress topayroll(only frominternal), sopayrollbehavior remains the same.
internal-policy is created and restricts egress from the internal pod to only the payroll and DB services.