Skip to main content

Configuring Network Policies

1. Creating NetworkPolicy

Field Description Example
metadata.name Name of the NetworkPolicy allow-frontend-to-backend
metadata.namespace Namespace where the policy is applied production
spec.podSelector Selects pods to apply the policy to {} matches all pods
spec.policyTypes Types of policies (Ingress, Egress) ["Ingress"]
spec.ingress Rules for incoming traffic [{from: [{podSelector: {matchLabels: {app: "frontend"}}]}]}
spec.egress Rules for outgoing traffic [{to: [{podSelector: {matchLabels: {app: "database"}}]}]}

Example: Basic Ingress Policy

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

Example: Egress Policy

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: restrict-db-access
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: database
  policyTypes:
    - Egress
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: backend
Note: NetworkPolicies are enforced by the CNI plugin (e.g., Calico, Cilium). Ensure your cluster supports network policies.

2. Defining Pod Selectors

Selector Type Description Example
matchLabels Defines key-value pairs to match pod labels
{
  "matchLabels": {
    "app": "frontend",
    "version": "v1"
  }
}
matchExpressions Allows for more complex label matching using operators
{
  "matchExpressions": [
    {
      "key": "environment",
      "operator": "In",
      "values": ["production", "staging"]
    }
  ]
}

Example: Using matchLabels

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

Example: Using matchExpressions

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dev-env
spec:
  podSelector:
    matchExpressions:
      - key: environment
        operator: In
        values: [development, staging]
  policyTypes:
    - Egress
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              name: monitoring

3. Configuring Ingress Rules

Field Description Example
ingress.rule Defines a rule for incoming traffic to the cluster host: example.com
ingress.rule.http.paths Specifies paths and backend services for HTTP traffic path: /api/v1
ingress.rule.http.paths.backend.service.name Name of the Kubernetes service to route traffic to name: api-service
ingress.rule.http.paths.backend.service.port.number Port number of the backend service port: 8080

Example: Basic Ingress Rule

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path: /api/v1
        backend:
          service:
            name: api-service
            port:
              number: 8080
Note: Ensure that the Ingress controller is installed and running in your cluster before applying these rules.

4. Configuring Egress Rules

Field Description Example
egress Defines the egress rules for the network policy [{ports: [{port: 53, protocol: "UDP"}]}]
ports Specifies the ports to allow egress traffic to [{port: 53, protocol: "UDP"}]
protocol Specifies the protocol (TCP, UDP, SCTP) "UDP"
to Defines the destination for egress traffic [{namespaceSelector: {matchLabels: {name: "prod"}}}]

Example: Allow Egress to DNS Server

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns-egress
spec:
  podSelector: {}
  policyTypes:
  - Egress
  egress:
  - ports:
    - port: 53
      protocol: UDP

Example: Allow Egress to Specific Namespace

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-egress-to-prod
spec:
  podSelector: {}
  policyTypes:
  - Egress
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          name: "prod"

5. Using Namespace Selectors

Field Description Example
metadata.namespace Namespace where the NetworkPolicy is defined default
spec.podSelector Selects pods based on labels; empty means all pods in namespace {} or {"app": "frontend"}
spec.namespaceSelector Selects namespaces using label selectors {"matchLabels": {"name": "production"}}

Example: Allow traffic from production namespace to default namespace

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-from-production
  namespace: default
spec:
  podSelector: {}
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: production
Note: The namespaceSelector field allows you to define rules that apply to all pods in a namespace matching the selector.

6. Allowing Specific Ports

Field Description Example
protocol Network protocol to allow (TCP, UDP, SCTP) TCP
port Port number to allow (1-65535) 80
endPort End of port range (optional) 8080

Example: Allow HTTP traffic on port 80

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

Example: Allow traffic on a port range

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-port-range
spec:
  podSelector:
    matchLabels:
      app: web
  policyTypes:
    - Ingress
  ingress:
    - ports:
        - protocol: TCP
          port: 8000
          endPort: 8010

7. Using IP Blocks

Field Description Example
ipBlock.cidr Specifies the IP block to allow or deny traffic from. Must be a valid CIDR notation. 10.0.0.0/8
ipBlock.except Optional list of CIDR blocks to exclude from the specified IP block. These are not affected by the policy. ["10.0.5.0/24"]

Example: Allow traffic from a specific IP block

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-ip-block
spec:
  podSelector: {}
  policyTypes:
    - Ingress
  ingress:
    - from:
        - ipBlock:
            cidr: 10.0.0.0/8

Example: Allow traffic from a specific IP block but exclude a subnet

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-ip-block-with-except
spec:
  podSelector: {}
  policyTypes:
    - Ingress
  ingress:
    - from:
        - ipBlock:
            cidr: 10.0.0.0/8
            except:
              - 10.0.5.0/24
Note: The ipBlock field is supported in Kubernetes v1.20+ and requires a network plugin that supports it (e.g., Calico, Cilium).

8. Implementing Default Deny All

Field Description Example
metadata.name Name of the NetworkPolicy default-deny-all
spec.podSelector Selects pods to apply policy to. Empty means all pods. {}
spec.policyTypes Policy types: Ingress, Egress. Must include Ingress for default deny. ["Ingress"]
spec.ingress Empty array = deny all traffic []

Example: Default Deny All Policy

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  ingress: []
Note: This policy blocks all ingress traffic to all pods in the namespace.

9. Testing Network Policies

Example: Testing Network Policy with curl

curl -s --connect-timeout 5 http://app-service:8080/api/data
Test Case Description Expected Result Command
Allow Ingress Verify that allowed traffic is permitted Response code 200 curl -s --max-time 5 http://app-service:8080/api/data
Deny Ingress Verify that denied traffic is blocked Timeout or connection refused curl -s --max-time 3 http://app-service:8080/api/data
Allow Egress Verify that allowed outbound traffic is permitted Response code 200 curl -s --max-time 5 https://external-api.com/data
Deny Egress Verify that denied outbound traffic is blocked Timeout or connection refused curl -s --max-time 3 https://external-api.com/data
Note: Use --max-time to prevent hanging tests. Ensure pods have proper labels for targeting.

Testing Steps Summary

  • Deploy test pods with appropriate labels
  • Apply network policies to control traffic
  • Use curl or similar tools to test connectivity
  • Validate results match expected policy behavior

10. Listing Network Policies

Command Description Notes
kubectl get networkpolicies List all NetworkPolicies in the current namespace Alias: np
kubectl get networkpolicies -A List all NetworkPolicies across all namespaces Useful for cluster-wide audit
kubectl get networkpolicies -n <namespace> List NetworkPolicies in a specific namespace Filter by namespace for targeted inspection

Example: Listing Network Policies in a Namespace

kubectl get networkpolicies -n production
NAME                POD-SELECTOR        POLICY-TYPE    AGE
allow-internal      app=backend         Egress         2d
Note: NetworkPolicies are namespace-scoped resources, so listing them in a specific namespace will only show policies defined within that namespace.

Was this article helpful?