Kubernetes Network Policy Allow Only HTTP Traffic to Your Web Application

Kubernetes Network Policy Allow Only HTTP Traffic to Your Web Application

Real-World Use Case: Restricting inbound traffic to your web application by allowing only HTTP (port 80) ensures that no other ports are exposed, reducing the attack surface for potential malicious activities.

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

Testing the Policy:

Deploy a web pod:
kubectl run web --image=nginx --labels=app=web --port=80 --restart=Never

Deploy a test client pod:
kubectl run test-client --image=busybox --restart=Never -- sleep 3600

Access the test-client pod and try to access the web pod:
kubectl exec -it test-client -- sh
wget -qO- http://web-ip

Expected Result: The request should succeed because port 80 is open.

Deleting Pods and Network Policy:

kubectl delete pod web
kubectl delete pod test-client
kubectl delete networkpolicy allow-http -n default