Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Kubernetes Network Policies

1. Introduction

Network Policies in Kubernetes are crucial for controlling the communication between pods and services within a cluster. By default, all pods can communicate with each other. Network Policies help enforce rules to restrict this communication based on defined criteria.

2. Key Concepts

2.1 Definitions

  • Pod: The smallest deployable unit in Kubernetes, which can contain one or more containers.
  • Network Policy: A specification of how groups of pods are allowed to communicate with each other and other network endpoints.
  • Selector: A mechanism to select a group of pods (based on labels) to which the network policy applies.

2.2 Types of Network Policies

  • Ingress Policies: Control the incoming traffic to the selected pods.
  • Egress Policies: Control the outgoing traffic from the selected pods.

3. Policy Configuration

3.1 Creating a Network Policy

Using the following YAML configuration, you can create a basic Network Policy:

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

This policy allows only pods with the label app: frontend to communicate with pods having the label app: nginx.

3.2 Egress Policy Example

Here's an example of an Egress Policy:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all-egress
  namespace: default
spec:
  podSelector: {}
  policyTypes:
  - Egress
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: database

This policy denies all egress traffic, allowing only pods with the label app: database to receive traffic from the selected pods.

4. Best Practices

  • Always start with a default deny policy to block all traffic.
  • Use specific pod selectors to limit the scope of the policy.
  • Regularly review and update network policies as your application evolves.
  • Test policies in a staging environment before deploying them to production.

5. FAQs

What happens if I do not define a Network Policy?

If no Network Policy is defined, all pods can communicate with each other by default.

Can I apply multiple Network Policies to the same pods?

Yes, multiple Network Policies can apply to the same pods. They are additive, and all rules must be satisfied for traffic to be allowed.

Do Network Policies work with all CNI plugins?

Network Policies are supported by most CNI plugins, but ensure your chosen plugin supports them.