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 topolicyTypes
: Which types of traffic are being controlled (Ingress
,Egress
, or both)ingress
: Incoming traffic rulesegress
: 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
- Isolate Pods: Prevent all communication to Pods except from those in the same namespace.
- Allow Specific External Access: Only allow egress traffic to specific external IPs.
- 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:
- Describe Policy:
kubectl describe networkpolicy <policy-name>
- Check Logs: Use logs to trace network activity.
- Use Diagnostic Tools: Like
ping
orcurl
for network checks.
Best Practices
- Least Privilege: Only allow necessary communications and deny all by default.
- Explicit Namespace Labels: Always use explicit labels for namespaces.
- Test Thoroughly: Make sure to test the policies in a dev environment first.
Complete Exercise: Setup, Steps, Troubleshooting, and Solution
Setup
- Create two namespaces:
project-a
andproject-b
kubectl create ns project-a
kubectl create ns project-b
- Label them:
kubectl label ns project-a project=my-project
kubectl label ns project-b other=not-my-project
Steps
- Apply the network policy to
project-a
.
kubectl apply -f network-policy.yaml -n project-a
- 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