Skip to main content
This article demonstrates a Kubernetes NetworkPolicy that restricts ingress to a database pod (CartsDB) by using pod labels. You will see the NetworkPolicy manifest, the Carts deployment that gets the required label, how to apply them with oc, and what to expect in the OpenShift web console.

NetworkPolicy: allow ingress only from labeled pods

Below is a simple NetworkPolicy that selects the CartsDB pods and permits ingress only from pods that carry the label cartsdbaccess: "true":
What this policy does:
  • podSelector.matchLabels.name: carts-db targets the CartsDB pods in the same namespace as the NetworkPolicy.
  • The ingress block allows traffic only from pods with the label cartsdbaccess: "true".
  • Any pod without that label cannot initiate inbound connections to the selected CartsDB pods.
Labels are case-sensitive and must match exactly between the NetworkPolicy and pod metadata. When a NetworkPolicy selects a pod and defines ingress rules, all ingress not explicitly allowed by any matching NetworkPolicy will be denied for that pod (assuming your CNI implements NetworkPolicy).

Carts deployment: grant database access via label

This Deployment creates the carts application pods and adds the cartsdbaccess: "true" label so they match the NetworkPolicy’s from.podSelector and can reach the CartsDB pods:
Because the pods created by this Deployment include cartsdbaccess: "true", they match the NetworkPolicy’s from.podSelector and are allowed inbound access to pods labeled name: carts-db. Apply the Carts deployment:
Example output:
After applying, the Carts pod should be running and will include the cartsdbaccess: "true" label that allows it to access the CartsDB pods.
A screenshot of the Red Hat OpenShift web console showing the "Pod details" page for pod carts-6945f489b-l2k78 (namespace: default) with its status listed as Running. The left sidebar displays the cluster navigation (Workloads → Pods, Deployments, etc.).

Apply the NetworkPolicy

Once your application pods have the correct label, apply the NetworkPolicy manifest:
Example output:
View the policy in the OpenShift (or Kubernetes) web console under Networking. The policy should show:
  • The pod selector targeting pods labeled name: carts-db.
  • The ingress rule that allows traffic only from pods labeled cartsdbaccess: "true".

Namespace scope and cross-namespace access

NetworkPolicy selectors are namespace-scoped by default. That means:
  • podSelector and from.podSelector only match pods in the same namespace as the NetworkPolicy.
  • To allow access from pods in other namespaces, include a namespaceSelector or use a combination of selectors.

Watch Video