⎈ A Hands-On Guide to Kubernetes: Network Policy 🛠️

⇢ Understanding Kubernetes Network Policy with Practical Examples

Anvesh Muppeda
6 min readJul 22, 2024
Kubernetes Network Policy by Anvesh Muppeda

Kubernetes Network Policies provide a robust mechanism to control the communication between pods and other network endpoints. They are essential for securing your applications by defining rules that specify how pods can communicate with each other and other network resources. In this hands-on guide, we will cover the fundamentals and demonstrate how to implement network policies with a practical example involving frontend and backend applications.

Table of Contents

  1. Introduction to Kubernetes Network Policies
  2. Prerequisites
  3. Understanding Network Policies
  4. Hands-On Example: Frontend and Backend Deployments
  5. Additional Kubernetes Network Policy Examples
  6. Troubleshooting Network Policies
  7. Conclusion
  8. Source Code

1. Introduction to Kubernetes Network Policies

Network Policies in Kubernetes are a crucial tool for securing your applications. They allow you to define rules that control how groups of pods can communicate with each other and other network resources. This is essential for isolating sensitive workloads and ensuring that only authorized traffic is allowed within your cluster.

2. Prerequisites

Before diving into Kubernetes Network Policies, ensure you have the following:

  • A basic understanding of Kubernetes concepts.
  • kubectl configured to interact with your cluster.
  • Running kubernetes cluster.

3. Understanding Network Policies

Network Policies are implemented using Kubernetes resources that define how pods are allowed to communicate with each other and other network endpoints. They use labels to select pods and define rules for ingress (incoming) and egress (outgoing) traffic.

Key Concepts:

  • Pod Selector: Selects the group of pods to which the policy applies.
  • Ingress Rules: Define allowed incoming traffic.
  • Egress Rules: Define allowed outgoing traffic.
  • Policy Types: Can be either ingress, egress, or both.
Animated Kubernetes Network Policy by Anvesh Muppeda

4. Hands-On Example: Frontend and Backend Deployments

In this example, we will create frontend and backend deployments and apply a Network Policy to secure the backend deployment, allowing communication only from the frontend deployment.

Step 1: Create the Frontend and Backend Deployments

Create a YAML file named deployments.yaml with the following content:

apiVersion: apps/v1
kind: Deployment
metadata:
name: backend-app
labels:
app: backend
spec:
replicas: 1
selector:
matchLabels:
app: backend
template:
metadata:
labels:
app: backend
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80

---

apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend-app
labels:
app: frontend
spec:
replicas: 1
selector:
matchLabels:
app: frontend
template:
metadata:
labels:
app: frontend
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80

Apply the deployments:

kubectl apply -f deployments.yaml

Step 2: Create the Network Policy for Backend

Create a YAML file named backend-network-policy.yaml with the following content:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: backend-network-policy
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
egress:
- to:
- podSelector:
matchLabels:
app: frontend

Apply the Network Policy:

kubectl apply -f backend-network-policy.yaml

Step 3: Verify the Network Policy

To verify that the Network Policy is working as expected, perform the following checks:

  1. Check Connectivity from Frontend to Backend
FRONTEND_POD=$(kubectl get pods -l app=frontend -o jsonpath='{.items[0].metadata.name}')
kubectl exec -it $FRONTEND_POD -- curl -sS $BACKEND_POD_IP

This should return the HTML content from the backend’s Nginx server.

$ kubectl exec -it $FRONTEND_POD -- curl -sS $BACKEND_POD_IP
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

2. Check Connectivity from Backend to Frontend

BACKEND_POD=$(kubectl get pods -l app=backend -o jsonpath='{.items[0].metadata.name}')
kubectl exec -it $BACKEND_POD -- curl -sS $FRONTEND_POD_IP

This should also return the HTML content from the frontend’s Nginx server.

kubectl exec -it $BACKEND_POD -- curl -sS $FRONTEND_POD_IP
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

3. Check Connectivity from External Sources

To ensure that the backend pod is not accessible from pods other than the frontend, try to curl the backend from a different pod (e.g., using a temporary busybox pod):

$ kubectl run busybox --image=busybox --rm -it -- /bin/sh
/ # wget --spider --timeout=1 $BACKEND_POD_IP

This should fail, indicating that the Network Policy is working correctly.

/ # wget --spider --timeout=1 10.244.0.87
Connecting to 10.244.0.87 (10.244.0.87:80)
wget: download timed out
/ #

Step 4: Cleanup

Once you’re done testing, you can delete the deployments and Network Policy:

kubectl delete -f deployments.yaml
kubectl delete -f backend-network-policy.yaml

5. Additional Kubernetes Network Policy Examples

Example 1: Allow All Ingress Traffic

This Network Policy allows all incoming traffic to the selected pods. It’s useful when you want to ensure that your pods are accessible from any source.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all-ingress
namespace: default
spec:
podSelector: {}
policyTypes:
- Ingress
ingress:
- {}

Explanation

  • podSelector: An empty selector means this policy applies to all pods in the namespace.
  • policyTypes: Specifies that this policy controls ingress traffic.
  • ingress: An empty ingress rule allows all incoming traffic.

Example 2: Deny All Egress Traffic

This Network Policy denies all outgoing traffic from the selected pods. It’s useful for highly secure environments where pods should not communicate externally.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all-egress
namespace: default
spec:
podSelector:
matchLabels:
app: secure-app
policyTypes:
- Egress
egress: []

Explanation

  • podSelector: Selects pods labeled app: secure-app.
  • policyTypes: Specifies that this policy controls egress traffic.
  • egress: An empty egress rule denies all outgoing traffic.

Example 3: Allow Ingress from a Specific Namespace

This Network Policy allows incoming traffic to the selected pods only from pods in a specific namespace.

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

Explanation

  • podSelector: Selects pods labeled app: my-app.
  • policyTypes: Specifies that this policy controls ingress traffic.
  • ingress: Allows incoming traffic from pods in the namespace labeled project: my-namespace.

Example 4: Allow Egress to a Specific IP Range

This Network Policy allows outgoing traffic from the selected pods to a specific IP range.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-egress-to-ip
namespace: default
spec:
podSelector:
matchLabels:
app: my-app
policyTypes:
- Egress
egress:
- to:
- ipBlock:
cidr: 192.168.1.0/24

Explanation

  • podSelector: Selects pods labeled app: my-app.
  • policyTypes: Specifies that this policy controls egress traffic.
  • egress: Allows outgoing traffic to the IP range 192.168.1.0/24.

Example 5: Allow Ingress Traffic on Specific Ports

This Network Policy allows incoming traffic to the selected pods only on specific ports.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-ingress-specific-ports
namespace: default
spec:
podSelector:
matchLabels:
app: web-app
policyTypes:
- Ingress
ingress:
- ports:
- protocol: TCP
port: 80
- protocol: TCP
port: 443

Explanation

  • podSelector: Selects pods labeled app: web-app.
  • policyTypes: Specifies that this policy controls ingress traffic.
  • ingress: Allows incoming traffic on ports 80 (HTTP) and 443 (HTTPS).

6. Troubleshooting Network Policies

  • Check Network Plugin: Ensure your CNI plugin supports Network Policies.
  • Pod Labels: Verify that pod labels match the selectors in your Network Policy.
  • Policy Types: Ensure you’ve specified the correct policy types (Ingress, Egress).
  • Logs and Events: Check the logs and events for errors related to Network Policies.

7. Conclusion

Kubernetes Network Policies are a powerful tool for securing your cluster by controlling pod communication. By understanding and implementing these policies, you can significantly enhance the security of your applications. Experiment with different policies and use this guide as a reference to master Network Policies in Kubernetes.

8. Source Code

You’re invited to explore our GitHub repository, which houses a comprehensive collection of source code for Kubernetes.

Also, if we welcome your feedback and suggestions! If you encounter any issues or have ideas for improvements, please open an issue on our GitHub repository. 🚀

Connect With Me

If you found this blog insightful and are eager to delve deeper into topics like AWS, cloud strategies, Kubernetes, or anything related, I’m excited to connect with you on LinkedIn. Let’s spark meaningful conversations, share insights, and explore the vast realm of cloud computing together.

Feel free to reach out, share your thoughts, or ask any questions. I look forward to connecting and growing together in this dynamic field!

My LinkedIn: https://www.linkedin.com/in/anveshmuppeda/

My GitHub: https://github.com/anveshmuppeda

Happy deploying! 🚀

Happy Kubernetings! ⎈

--

--

Anvesh Muppeda
Anvesh Muppeda

Written by Anvesh Muppeda

🤝Cloud Architect & DevOps Engineer || Kubernetes ⎈ & Docker ⛴️ aficionado || CKA || CKAD || AWS SAA || Connect with me on www.linkedin.com/in/anveshmuppeda

No responses yet