Skip to main content

Implementing Network Policies

1. Understanding Mesh Network Policies

Policy Type Description Use Case Example
TrafficPolicy Defines how traffic is routed between services Control traffic flow, apply timeouts and retries
trafficPolicy:
  timeout: 5s
  retry:
    attempts: 3
    perTryTimeout: 2s
DestinationRule Applies to a specific service, configures traffic policies and load balancing Define circuit breaker settings, TLS configuration
destinationRule:
  host: api-service
  trafficPolicy:
    connectionPool:
      http:
        maxRequestsPerConnection: 10
VirtualService Defines how to route traffic to a service Implement A/B testing, fault injection, request/response transformations
virtualService:
  hosts:
    - api-service
  http:
    - route:
        - destination:
            host: api-service-v1
PeerAuthentication Enforces mutual TLS between services Secure service-to-service communication
peerAuthentication:
  mtls:
    mode: STRICT

Example: Applying a Traffic Policy

apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: api-destination-rule
spec:
  host: api-service
  trafficPolicy:
    connectionPool:
      http:
        maxRequestsPerConnection: 10
    outlierDetection:
      consecutiveErrors: 5
      interval: 10s
      baseEjectionTime: 30s
Note: Mesh network policies are applied at the service level and can be scoped to specific namespaces or workloads.

2. Configuring Ingress Rules

Rule Type Description Example
ingress.host Host name for the ingress rule api.example.com
ingress.path Path pattern to match /api/v1/
ingress.backend.serviceName Name of the backend service backend-service
ingress.backend.servicePort Port number of the backend service 8080

Example: Basic Ingress Rule Configuration

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress
spec:
  rules:
  - host: api.example.com
    http:
      paths:
      - path: /api/v1/
        pathType: Prefix
        backend:
          service:
            name: backend-service
            port:
              number: 8080
Note: The pathType field determines how the path is matched. Common values are Exact, Prefix, and ImplementationSpecific.

3. Configuring Egress Rules

Rule Type Description Example
egress.allow Allows traffic to specific destinations
[
  {
    "destination": {
      "addresses": ["10.0.0.0/8"],
      "ports": [80, 443]
    }
  }
]
egress.deny Denies traffic to specific destinations
[
  {
    "destination": {
      "addresses": ["172.16.0.0/12"],
      "ports": [22]
    }
  }
]

Example: Egress Rule Configuration

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: egress-policy
spec:
  podSelector: {}
  policyTypes:
  - Egress
  egress:
  - to:
    - ipBlock:
        cidr: 10.0.0.0/8
    ports:
    - protocol: TCP
      port: 80
    - protocol: TCP
      port: 443
Note: Egress rules in Kubernetes Network Policies control traffic flowing from pods to external destinations. These policies are applied after the pod's own network namespace is configured.

4. Implementing Namespace Isolation

Policy Type Description Example
Namespace Isolation Restricts network access between namespaces using labels and selectors.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: namespace-isolation
  namespace: production
spec:
  podSelector: {}
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              name: frontend
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              name: backend

Example: Isolating Production Namespace

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: isolate-production
  namespace: production
spec:
  podSelector: {}
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              name: frontend
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              name: external
Note: This policy ensures that only pods in the frontend namespace can access pods in the production namespace, and only pods in the external namespace can be accessed from pods in the production namespace.

Key Concepts

  • Namespace Selectors allow policies to target specific namespaces.
  • Ingress/Egress control traffic flow into and out of the namespace.
  • Pod Selectors can be used to further refine which pods are affected.

5. Setting CIDR-Based Rules

Rule Type CIDR Block Action Description
ingress 192.168.1.0/24 allow Allow traffic from internal network
egress 0.0.0.0/0 deny Deny all outbound traffic by default
ingress 10.0.0.0/8 allow Allow traffic from private network

Example: Applying CIDR Rules in Kubernetes Network Policy

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: cidr-policy
spec:
  podSelector: {}
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - ipBlock:
            cidr: 192.168.1.0/24
  egress:
    - to:
        - ipBlock:
            cidr: 0.0.0.0/0
Note: Ensure that the ipBlock is correctly formatted with CIDR notation to avoid misconfigurations.

6. Configuring Port-Based Rules

Rule Type Port Specification Description Example
Ingress Rule 80, 443 Allow traffic to specific ports from specified sources
{
  "ingress": [
    {
      "from": [
        {
          "podSelector": {
            "matchLabels": {
              "app": "frontend"
            }
          }
        }
      ],
      "ports": [
        {
          "protocol": "TCP",
          "port": 80
        }
      ]
    }
  ]
}
Egress Rule 53, 8080 Allow traffic from specific ports to specified destinations
{
  "egress": [
    {
      "to": [
        {
          "namespaceSelector": {
            "matchLabels": {
              "name": "external"
            }
          }
        }
      ],
      "ports": [
        {
          "protocol": "UDP",
          "port": 53
        }
      ]
    }
  ]
}

Example: Allow Ingress on Port 80

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-ingress-to-http
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 80

Example: Egress to DNS on Port 53

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-egress-to-dns
spec:
  podSelector:
    matchLabels:
      app: app
  policyTypes:
  - Egress
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          name: external
    ports:
    - protocol: UDP
      port: 53

7. Implementing Protocol-Based Rules

Rule Type Protocol Description Example
HTTP HTTP Applies to HTTP traffic, supports path and method matching
{
  "match": {
    "method": "GET",
    "path": "/api/v1/users"
  }
}
HTTPS HTTPS Applies to HTTPS traffic, includes TLS termination and SNI matching
{
  "match": {
    "sni": "api.example.com"
  }
}
TCP TCP Applies to TCP traffic, supports port and IP matching
{
  "match": {
    "port": 8080,
    "ip": "192.168.1.0/24"
  }
}
UDP UDP Applies to UDP traffic, supports port and IP matching
{
  "match": {
    "port": 53,
    "ip": "10.0.0.0/8"
  }
}
gRPC gRPC Applies to gRPC traffic, supports service and method matching
{
  "match": {
    "service": "UserService",
    "method": "GetUser"
  }
}

Example: HTTP Protocol Rule

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: http-policy
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: frontend
    ports:
    - protocol: TCP
      port: 80
    http:
      path: /api/v1/users
      method: GET

Example: TCP Protocol Rule

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: tcp-policy
spec:
  podSelector:
    matchLabels:
      app: database
  policyTypes:
  - Egress
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          name: backend
    ports:
    - protocol: TCP
      port: 5432

8. Managing Policy Enforcement Mode

Mode Description Default Notes
enforcementMode Controls how policies are enforced in the service mesh enabled Applies to all policies in the mesh
enforcementMode disabled Disables all policy enforcement Use for testing or debugging
enforcementMode permissive Allows traffic but logs violations Use for gradual migration or compliance validation

Example: Setting Enforcement Mode

apiVersion: networking.istio.io/v1beta1
kind: MeshConfig
metadata:
  name: istio
spec:
  policy:
    enforcementMode: <span class="highlight">permissive</span>
Note: permissive mode is useful for validating policies without disrupting traffic.

9. Integrating with Kubernetes Network Policies

Feature Description Integration Method Notes
Service Mesh Policy Defines traffic control rules within the mesh Uses Istio's NetworkPolicy or PeerAuthentication Can be extended to integrate with Kubernetes Network Policies
K8s Network Policy Enforces network access control at the pod level Uses NetworkPolicy CRD in Kubernetes Can be used to restrict traffic to and from service mesh components
Traffic Direction Controls traffic flow between services in the mesh Configured via DestinationRule and VirtualService Can be restricted by Kubernetes Network Policies to specific pods or namespaces

Example: Integrating Service Mesh with K8s Network Policies

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-mesh-traffic
spec:
  podSelector:
    matchLabels:
      app: service-mesh
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: istio-system
    ports:
    - protocol: TCP
      port: 15001
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          name: istio-system
    ports:
    - protocol: TCP
      port: 15001
Note: Ensure that the service mesh's control plane (e.g., Istio) is configured to allow traffic from and to the Kubernetes network policies.

10. Troubleshooting Network Policies

Example: Checking Policy Application

kubectl get networkpolicies -n <namespace>
kubectl describe networkpolicy <policy-name> -n <namespace>
Issue Possible Cause Solution
Traffic Not Blocked Policy not applied to pods Verify pod labels match policy selectors
Unexpected Allowance Conflicting policy with higher precedence Check policy order and overlap
Policy Not Applied Missing namespace or incorrect scope Ensure policy is in correct namespace
Note: Use kubectl describe to inspect policy details and understand how rules are applied.

Workflow: Debugging Policy Issues

  1. Check if the network policy is applied to the namespace
  2. Verify pod labels match selectors in the policy
  3. Confirm traffic direction (ingress/egress)
  4. Review policy rule precedence
  5. Use kubectl logs to inspect service mesh control plane logs

11. Implementing Network Policy Testing

Example: Testing Network Policies with kubectl

kubectl run -it --rm debug-pod --image=busybox --restart=Never -- /bin/sh -c "wget -qO- http://backend-service:8080"
Test Type Description Command Notes
Connectivity Test Verify if pods can communicate with each other kubectl exec <pod-name> -- wget -qO- http://target-service:port Use this to check if network policies allow traffic between pods
Policy Enforcement Check if a specific policy is enforcing rules kubectl describe networkpolicy <policy-name> Shows the rules and status of a network policy
Note: Network policy testing should be done in a staging environment before applying to production.

Testing Approaches Comparison

  • Manual Testing: Using kubectl exec to simulate traffic
  • Automated Testing: Using tools like istioctl or custom scripts to validate policies
  • Integration Testing: Running tests as part of CI/CD pipeline to ensure policies are applied correctly

12. Managing Network Policy Precedence

Policy Type Priority Range Description
Kubernetes NetworkPolicy 0 - 1000 Standard Kubernetes network policies with configurable priority
Service Mesh Policy 1001 - 2000 Service mesh specific policies (e.g., Istio, Linkerd)
Namespace Default Policy 2001 - 3000 Default policies applied to all namespaces (e.g., allow all)

Example: Setting Policy Precedence in Kubernetes

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-namespace-traffic
  namespace: production
spec:
  priority: 500
  podSelector: {}
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: frontend
Note: Higher priority values are processed first. Policies with the same priority are processed in a non-deterministic order.

Was this article helpful?