Kubernetes Network Policies are crucial for controlling the communication between Pods. By default, every Pod can communicate with every other Pod in the cluster. Network Policies enable you to enforce which Pods can communicate with each other and with resources outside the cluster.

Defining Network Policies

To create a Network Policy, you typically define it in a YAML file. The key components are:

  • podSelector: To select the Pods the policy applies to
  • policyTypes: Which types of traffic are being controlled (Ingress, Egress, or both)
  • ingress: Incoming traffic rules
  • egress: Outgoing traffic rules

Here is an example YAML file that allows incoming traffic from a specific namespace.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-namespace-traffic
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          project: my-project

To apply it, use:

kubectl apply -f network-policy.yaml

Take into account that you cannot create Network Policies imperatively, you can type netpol in the search and copy an example, beware that the example has a namespace that you need to change.

Common Use Cases

  1. Isolate Pods: Prevent all communication to Pods except from those in the same namespace.
  2. Allow Specific External Access: Only allow egress traffic to specific external IPs.
  3. Microservice Segmentation: Restrict services to only be able to communicate with specific services.

Validating and Troubleshooting Network Policies

To validate if your network policy is applied:

  1. Describe Policy:
kubectl describe networkpolicy <policy-name>
  1. Check Logs: Use logs to trace network activity.
  2. Use Diagnostic Tools: Like ping or curl for network checks.

Best Practices

  1. Least Privilege: Only allow necessary communications and deny all by default.
  2. Explicit Namespace Labels: Always use explicit labels for namespaces.
  3. Test Thoroughly: Make sure to test the policies in a dev environment first.

Complete Exercise: Setup, Steps, Troubleshooting, and Solution

Setup

  1. Create two namespaces: project-a and project-b
kubectl create ns project-a
kubectl create ns project-b
  1. Label them:
kubectl label ns project-a project=my-project
kubectl label ns project-b other=not-my-project

Steps

  1. Apply the network policy to project-a.
kubectl apply -f network-policy.yaml -n project-a
  1. Test the policy by initiating traffic from project-b.

Troubleshooting

  • Make sure the namespaces are labeled correctly.
  • Use kubectl describe to examine the network policy.

Solution

If set up correctly, Pods in project-a should only accept traffic from other Pods labeled with project=my-project.

Tip: Practice Network Policies here