Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
K8s Networking Kubernetes Kubernetes: From Zero to Production Module 4 - Services and Networking security

NetworkPolicies - Controlling Pod-to-Pod Traffic

Reviewed & accurate
AI Summary

What You Will Learn

Advanced

  • What NetworkPolicies are
  • How to restrict traffic
  • Default deny patterns

A NetworkPolicy controls traffic between Pods. By default, all Pods can communicate. NetworkPolicies restrict traffic for security.

Default: all traffic allowed
Without NetworkPolicies, any Pod can talk to any other Pod. In production, use a default-deny policy and only allow necessary traffic.
networkpolicy.yamlyaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-policy
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: database    # Apply to DB Pods
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: api     # Only allow traffic from API Pods
    ports:
    - protocol: TCP
      port: 5432       # Only on port 5432

Default Deny Pattern

Terminalyaml
# Deny ALL ingress to ALL Pods in a namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
spec:
  podSelector: {}     # Selects all Pods
  policyTypes:
  - Ingress
  ingress: []          # No ingress allowed
NetworkPolicy support
Not all K8s networking plugins support NetworkPolicies. Calico, Cilium, and Weave support them. The default flannel plugin does NOT. Check your CNI plugin.

Practical Exercise

Check your CNI plugin: kubectl get pods -n kube-system
Create a default-deny NetworkPolicy
Test: Pods cannot communicate
Create a policy allowing API to DB
Test: API can reach DB, others cannot

Key Takeaways

  • NetworkPolicy = firewall for Pods.
  • Default: ALL traffic allowed (insecure!).
  • Use default-deny + allow specific traffic.
  • Needs a compatible CNI plugin (Calico, Cilium).
  • Restrict by: podSelector, namespaceSelector, IPBlock.
Previously: Lesson 22 covered DNS.
Today: You learned: Firewall rules for Pod traffic.
Next: Lesson 24 covers troubleshooting.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments