KAHIBARO Bookshelves
Discord Login Register

8.3. Network policies

Concept and Scope of NetworkPolicies

Network policies in OpenShift define how pods are allowed to communicate with each other and with other network endpoints. They are Kubernetes NetworkPolicy objects, enforced by the cluster’s CNI plugin, and apply at the pod level (L3/L4 – IP and port).

Key points:

  • Policies are namespaced: they only affect pods and traffic within a given namespace (plus ingress/egress across namespaces as selected).
  • Policies are deny-by-default per selected pod: once any NetworkPolicy selects a pod for a given direction (ingress or egress), that pod’s traffic in that direction is allowed only as explicitly specified.
  • Policies are additive: multiple policies combine to grant more allowed traffic. If any policy permits a particular connection, it’s allowed (subject to other controls like firewalls and Security Context Constraints).

Basic Structure of a NetworkPolicy

A NetworkPolicy resource has a standard shape:

  • podSelector: which pods this policy applies to.
  • policyTypes: Ingress, Egress, or both.
  • ingress: rules describing who can talk to the selected pods and on which ports.
  • egress: rules describing where the selected pods can talk to and on which ports.

Minimal example – allow only HTTP traffic from pods labeled role=frontend to pods labeled role=backend in the same namespace:

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

Interpretation:

  • The policy applies to all pods with role=backend.
  • For ingress traffic, only:
    • Traffic from pods with role=frontend in the same namespace,
    • To TCP port 8080,
      is allowed.
  • Any other inbound traffic to role=backend pods is denied (once this policy is in effect).

Selecting Pods and Traffic Sources

Target pods: `podSelector`

podSelector defines which pods are protected by the policy:

  • podSelector: {} (empty) → select all pods in the namespace.
  • Label-based selection → only pods matching those labels.

Example – apply to all pods in payments namespace:

spec:
  podSelector: {}
  policyTypes: [Ingress]
  ingress:
    - {}  # some rules

Example – apply only to application pods:

spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/part-of: my-service

Sources/destinations: `from` and `to`

Within ingress and egress rules, you define where traffic can come from or go to using:

  • podSelector: pods (within the same namespace if no namespaceSelector is used).
  • namespaceSelector: namespaces with particular labels.
  • ipBlock: IP CIDRs, usually for external or non-pod traffic.

Pod-based selection

Allow traffic from any pod with label team=analytics in the same namespace:

ingress:
  - from:
      - podSelector:
          matchLabels:
            team: analytics

Cross-namespace selection

Allow traffic from pods in namespaces labeled env=staging:

ingress:
  - from:
      - namespaceSelector:
          matchLabels:
            env: staging

Combine pod and namespace selectors to restrict to certain pods in specific namespaces:

ingress:
  - from:
      - namespaceSelector:
          matchLabels:
            env: staging
        podSelector:
          matchLabels:
            role: api-client

IP-based selection (`ipBlock`)

ipBlock is useful to allow or deny traffic to/from external networks.

Allow traffic from a corporate subnet except a management range:

ingress:
  - from:
      - ipBlock:
          cidr: 10.0.0.0/16
          except:
            - 10.0.10.0/24

Notes:

  • ipBlock applies to IP addresses, not pod labels.
  • It is commonly used to define access from on-prem networks, VPNs, or specific external ranges.

Controlling Ports and Protocols

Network policies operate at TCP/UDP/SCTP layer with optional ports:

ports:
  - protocol: TCP
    port: 80
  - protocol: TCP
    port: 443

If ports is omitted:

  • All ports are allowed for the specified source/destination.
  • Protocol defaults to TCP if port is a name; generally you should set protocol.

You can also use named ports defined in the pod’s container spec:

ports:
  - port: http  # name defined in containerPorts

Ingress vs Egress Policies

Ingress policies

Control traffic into selected pods.

Example – only allow:

  • Internal calls from namespace frontend,
  • From pods with role=web,
  • On port 443.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: backend-ingress
  namespace: payments
spec:
  podSelector:
    matchLabels:
      app: payments-api
  policyTypes:
    - Ingress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              team: frontend
          podSelector:
            matchLabels:
              role: web
      ports:
        - protocol: TCP
          port: 443

Once this policy is applied, all other inbound traffic to app=payments-api pods is blocked.

Egress policies

Control outbound traffic from selected pods.

Example – limit outgoing connections from app=payments-api to:

  • The database namespace on port 5432.
  • A specific external IP range for an API provider.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: payments-egress
  namespace: payments
spec:
  podSelector:
    matchLabels:
      app: payments-api
  policyTypes:
    - Egress
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              name: databases
          podSelector:
            matchLabels:
              app: postgres
      ports:
        - protocol: TCP
          port: 5432
    - to:
        - ipBlock:
            cidr: 203.0.113.0/24
      ports:
        - protocol: TCP
          port: 443

When at least one egress policy selects these pods, all other outgoing traffic is denied, including DNS, unless explicitly allowed.

Typical Policy Patterns in OpenShift

Default deny for a namespace

A common security posture is to deny all traffic by default and explicitly allow necessary flows.

Deny all ingress to pods in a namespace:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all-ingress
  namespace: my-namespace
spec:
  podSelector: {}
  policyTypes:
    - Ingress
  ingress: []

Deny all egress:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all-egress
  namespace: my-namespace
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress: []

Use these as a baseline, then add more specific allow policies.

Allow same-namespace traffic

After a default deny, you might allow all pods in the same namespace to talk to each other:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-same-namespace
  namespace: my-namespace
spec:
  podSelector: {}
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector: {}

This still blocks cross-namespace and external traffic, while permitting intra-namespace communication.

Layered policies for a microservice

For a backend microservice:

  1. Default deny ingress for the namespace.
  2. Specific policy to allow ingress from only selected frontends.
  3. Specific egress policy to limit dependencies.

Example set:



# 1. Default deny
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: shop
spec:
  podSelector: {}
  policyTypes: [Ingress]
  ingress: []
# 2. Allow frontend to backend
kind: NetworkPolicy
metadata:
  name: allow-web-to-orders
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: orders
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: web
      ports:
        - protocol: TCP
          port: 8080
# 3. Egress from backend only to db
kind: NetworkPolicy
metadata:
  name: orders-egress
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: orders
  policyTypes: [Egress]
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              name: databases
          podSelector:
            matchLabels:
              app: orders-db
      ports:
        - protocol: TCP
          port: 5432

OpenShift-Specific Considerations

Interaction with OpenShift SDN and OVN-K

OpenShift supports different network plugins (e.g. OpenShift SDN, OVN-Kubernetes). Both implement Kubernetes NetworkPolicy, but capabilities and performance characteristics can differ.

From a user perspective:

  • Use standard NetworkPolicy manifests.
  • Rely on label-based selection and namespaces; avoid relying on implementation-specific behavior.
  • Be aware that some advanced features (e.g. additional CRDs or extended policy constructs) might be specific to one plugin and not portable.

Namespaces and tenant isolation

OpenShift commonly uses namespaces as an isolation boundary between teams or applications. Network policies:

  • Strengthen tenant isolation by blocking cross-namespace pod-to-pod communication unless explicitly allowed.
  • Work together with authorization (who can create/modify policies) to enforce isolation policies.

A typical multi-tenant pattern:

  • Label each project/namespace with tenant=<name>.
  • Apply default-deny ingress/egress per tenant.
  • Explicitly create policies only where cross-tenant communication is required.

Interaction with Routes and external access

Network policies only control pod-level traffic. They do not directly manage:

  • Which Routes expose services externally.
  • External load balancer configuration.

However, they can affect traffic that originates from:

  • Routers (ingress controllers) running as pods.
  • Node-local processes or external IPs, depending on CNI behavior.

Practical implication:

  • If you lock down ingress policies to only allow certain namespaces/pods, ensure that:
    • Router or ingress pods are allowed by your from rules.
    • Any other in-cluster component that must access the service is included.

Example – allow traffic from the default router namespace to your app:

ingress:
  - from:
      - namespaceSelector:
          matchLabels:
            network.openshift.io/policy-group: ingress

(Exact labels may vary; in practice you should check how router namespaces are labeled in your cluster.)

DNS and Egress Gotchas

When applying egress policies:

  • Pods often need to reach:
    • Cluster DNS (CoreDNS or equivalent).
    • Cluster services (e.g. for service discovery, metrics).
    • External APIs.

If you create a strict egress policy, you must explicitly allow DNS:

Example – allow DNS and specific external HTTPS:

spec:
  podSelector:
    matchLabels:
      app: my-service
  policyTypes: [Egress]
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: openshift-dns
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53
    - to:
        - ipBlock:
            cidr: 198.51.100.0/24
      ports:
        - protocol: TCP
          port: 443

Labels and namespaces for DNS may differ; inspect your cluster to identify the correct selectors.

Designing Network Policies Incrementally

Because policies can easily block traffic, an incremental approach is safer:

  1. Start with observation
    • Understand current communication patterns.
    • Document which pods/services talk to which, and on what ports.
  2. Introduce soft boundaries
    • Begin with less restrictive policies that allow known traffic patterns without yet adding global default denies.
    • Use labels to structure your application: tier, role, team, etc.
  3. Add default deny per namespace
    • After validating specific allow policies, introduce default deny for ingress (and optionally egress).
    • Monitor for any broken flows and adjust rules.
  4. Refine and group
    • Group common rules into reusable patterns (e.g. “allow monitoring namespace to scrape metrics”).
    • Standardize labels across teams to simplify selectors.

Testing and Troubleshooting Network Policies

When a pod cannot reach another:

  1. Check whether any NetworkPolicy exists in the source or destination namespace.
  2. For ingress issues:
    • Inspect policies with policyTypes: Ingress that select the destination pod.
    • Confirm that the source is allowed in from and correct port is open.
  3. For egress issues:
    • Inspect policies with policyTypes: Egress that select the source pod.
    • Confirm that the destination (pod, namespace, or IP) and port are allowed.
  4. Temporarily relax policies:
    • As a diagnostic step, you can add a policy that broadens access (e.g. allow from all pods) to verify if policies are the root cause, then tighten again.

Example quick diagnostic policy (namespace-local ingress allow):

kind: NetworkPolicy
metadata:
  name: debug-allow-all-ingress
  namespace: my-namespace
spec:
  podSelector: {}
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector: {}

Remove diagnostic policies once you identify the issue to restore your intended security posture.

Best Practices for Network Policies in OpenShift

  • Label consistently: define a standard label taxonomy for apps, tiers, teams, and environments to simplify policy rules.
  • Default deny then allow: prefer explicit allowlists to implicit open access.
  • Separate concerns:
    • One policy for default deny.
    • Separate policies for application flows, monitoring, logging, and external access.
  • Version control policies: treat NetworkPolicy manifests like application code (Git, review, testing).
  • Document intent: use metadata.annotations and descriptive names to clarify what each policy is supposed to do.
  • Coordinate with other security layers: NetworkPolicies complement, not replace:
    • Role-Based Access Control.
    • Security Context Constraints.
    • Image security and compliance settings.
  • Periodically review: remove obsolete rules, check for overly permissive patterns, and ensure new services are covered.

These practices help you use network policies as an effective, maintainable tool for in-cluster traffic control and multi-tenant isolation in OpenShift.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Course Overview
    • ☰ 1.1. What is OpenShift
      • ☰ 1.2. Why OpenShift is used in modern IT and cloud environments
        • ☰ 1.3. OpenShift vs Kubernetes
          • ☰ 1.4. Typical OpenShift use cases
            • ☰ 1.5. Structure and goals of the course
            • ☰ 2. Containers and Cloud-Native Fundamentals
              • ☰ 2.1. What is a container
                • ☰ 2.2. Containers vs virtual machines
                  • ☰ 2.3. Introduction to Docker and container images
                    • ☰ 2.4. Container registries
                      • ☰ 2.5. Basics of cloud-native applications
                      • ☰ 3. Kubernetes Fundamentals
                        • ☰ 3.1. What is Kubernetes
                          • ☰ 3.2. Kubernetes architecture
                            • ☰ 3.3. Control plane components
                              • ☰ 3.4. Worker node components
                                • ☰ 3.5. Kubernetes objects and resources
                                  • ☰ 3.6. Declarative configuration model
                                  • ☰ 4. OpenShift Architecture
                                    • ☰ 4.1. Overview of OpenShift architecture
                                      • ☰ 4.2. Control plane in OpenShift
                                        • ☰ 4.3. Nodes and machine roles
                                          • ☰ 4.4. OpenShift Operators
                                            • ☰ 4.5. OpenShift networking model
                                              • ☰ 4.6. OpenShift storage model
                                              • ☰ 5. OpenShift Installation and Deployment Models
                                                • ☰ 5.1. OpenShift deployment options
                                                  • ☰ 5.2. Installer-Provisioned Infrastructure
                                                    • ☰ 5.3. User-Provisioned Infrastructure
                                                      • ☰ 5.4. Managed OpenShift services
                                                        • ☰ 5.5. Single-node OpenShift
                                                          • ☰ 5.6. Cluster lifecycle management
                                                          • ☰ 6. Accessing and Using OpenShift
                                                            • ☰ 6.1. OpenShift web console
                                                              • ☰ 6.2. OpenShift CLI (oc)
                                                                • ☰ 6.3. Authentication and authorization
                                                                  • ☰ 6.4. Projects and namespaces
                                                                    • ☰ 6.5. Resource quotas and limits
                                                                    • ☰ 7. Building and Deploying Applications
                                                                      • ☰ 7.1. Application deployment concepts
                                                                        • ☰ 7.2. Source-to-Image (S2I)
                                                                          • ☰ 7.3. Container-based deployments
                                                                            • ☰ 7.4. DeploymentConfigs and Deployments
                                                                              • ☰ 7.5. Rolling updates and rollbacks
                                                                              • ☰ 8. Networking in OpenShift
                                                                                • ☰ 8.1. Services and service discovery
                                                                                  • ☰ 8.2. Routes and ingress
                                                                                    • ☰ 8.3. Network policies
                                                                                      • ☰ 8.4. Load balancing
                                                                                        • ☰ 8.5. External access to applications
                                                                                        • ☰ 9. Storage in OpenShift
                                                                                          • ☰ 9.1. Persistent storage concepts
                                                                                            • ☰ 9.2. Persistent Volumes
                                                                                              • ☰ 9.3. Persistent Volume Claims
                                                                                                • ☰ 9.4. StorageClasses
                                                                                                  • ☰ 9.5. Dynamic provisioning
                                                                                                    • ☰ 9.6. Stateful applications
                                                                                                    • ☰ 10. Configuration and Secrets Management
                                                                                                      • ☰ 10.1. ConfigMaps
                                                                                                        • ☰ 10.2. Secrets
                                                                                                          • ☰ 10.3. Environment variables
                                                                                                            • ☰ 10.4. Managing sensitive data
                                                                                                              • ☰ 10.5. Best practices for configuration
                                                                                                              • ☰ 11. Scaling and High Availability
                                                                                                                • ☰ 11.1. Horizontal pod autoscaling
                                                                                                                  • ☰ 11.2. Vertical scaling
                                                                                                                    • ☰ 11.3. Self-healing and pod restarts
                                                                                                                      • ☰ 11.4. High availability concepts
                                                                                                                        • ☰ 11.5. Multi-zone and multi-region clusters
                                                                                                                        • ☰ 12. Monitoring, Logging, and Observability
                                                                                                                          • ☰ 12.1. Built-in monitoring stack
                                                                                                                            • ☰ 12.2. Metrics and alerts
                                                                                                                              • ☰ 12.3. Logging architecture
                                                                                                                                • ☰ 12.4. Distributed tracing
                                                                                                                                  • ☰ 12.5. Troubleshooting applications
                                                                                                                                  • ☰ 13. Security in OpenShift
                                                                                                                                    • ☰ 13.1. Security model overview
                                                                                                                                      • ☰ 13.2. Role-Based Access Control
                                                                                                                                        • ☰ 13.3. Security Context Constraints
                                                                                                                                          • ☰ 13.4. Image security and scanning
                                                                                                                                            • ☰ 13.5. Network security
                                                                                                                                              • ☰ 13.6. Compliance and auditing
                                                                                                                                              • ☰ 14. CI/CD and DevOps with OpenShift
                                                                                                                                                • ☰ 14.1. DevOps concepts
                                                                                                                                                  • ☰ 14.2. CI/CD pipelines overview
                                                                                                                                                    • ☰ 14.3. OpenShift Pipelines (Tekton)
                                                                                                                                                      • ☰ 14.4. GitOps with Argo CD
                                                                                                                                                        • ☰ 14.5. Integrating OpenShift with external CI tools
                                                                                                                                                        • ☰ 15. Operators and Platform Services
                                                                                                                                                          • ☰ 15.1. What are Operators
                                                                                                                                                            • ☰ 15.2. Operator Lifecycle Manager
                                                                                                                                                              • ☰ 15.3. Installing and managing Operators
                                                                                                                                                                • ☰ 15.4. Common platform Operators
                                                                                                                                                                  • ☰ 15.5. Custom Operators
                                                                                                                                                                  • ☰ 16. Upgrades, Maintenance, and Operations
                                                                                                                                                                    • ☰ 16.1. OpenShift upgrade process
                                                                                                                                                                      • ☰ 16.2. Backup and restore
                                                                                                                                                                        • ☰ 16.3. Node maintenance
                                                                                                                                                                          • ☰ 16.4. Cluster troubleshooting
                                                                                                                                                                            • ☰ 16.5. Capacity planning
                                                                                                                                                                            • ☰ 17. OpenShift on HPC and Specialized Workloads
                                                                                                                                                                              • ☰ 17.1. Running batch workloads on OpenShift
                                                                                                                                                                                • ☰ 17.2. OpenShift and GPUs
                                                                                                                                                                                  • ☰ 17.3. MPI and parallel workloads in containers
                                                                                                                                                                                    • ☰ 17.4. Hybrid HPC and cloud workflows
                                                                                                                                                                                    • ☰ 18. OpenShift in Practice
                                                                                                                                                                                      • ☰ 18.1. Typical OpenShift workflows
                                                                                                                                                                                        • ☰ 18.2. Development to production lifecycle
                                                                                                                                                                                          • ☰ 18.3. Case studies from industry
                                                                                                                                                                                            • ☰ 18.4. Common pitfalls and best practices
                                                                                                                                                                                            • ☰ 19. Future Directions and Ecosystem
                                                                                                                                                                                              • ☰ 19.1. Kubernetes ecosystem overview
                                                                                                                                                                                                • ☰ 19.2. OpenShift roadmap
                                                                                                                                                                                                  • ☰ 19.3. Serverless and event-driven workloads
                                                                                                                                                                                                    • ☰ 19.4. AI and data platforms on OpenShift
                                                                                                                                                                                                    • ☰ 20. Final Project and Hands-On Exercises
                                                                                                                                                                                                      • ☰ 20.1. Deploying a containerized application
                                                                                                                                                                                                        • ☰ 20.2. Implementing CI/CD with OpenShift
                                                                                                                                                                                                          • ☰ 20.3. Securing and scaling an application
                                                                                                                                                                                                            • ☰ 20.4. Monitoring and troubleshooting report