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 labelcartsdbaccess: "true":
podSelector.matchLabels.name: carts-dbtargets the CartsDB pods in the same namespace as the NetworkPolicy.- The
ingressblock allows traffic only from pods with the labelcartsdbaccess: "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 thecarts application pods and adds the cartsdbaccess: "true" label so they match the NetworkPolicy’s from.podSelector and can reach the CartsDB pods:
cartsdbaccess: "true", they match the NetworkPolicy’s from.podSelector and are allowed inbound access to pods labeled name: carts-db.
Apply the Carts deployment:
cartsdbaccess: "true" label that allows it to access the CartsDB pods.

Apply the NetworkPolicy
Once your application pods have the correct label, apply the NetworkPolicy manifest:- 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:podSelectorandfrom.podSelectoronly match pods in the same namespace as the NetworkPolicy.- To allow access from pods in other namespaces, include a
namespaceSelectoror use a combination of selectors.
Links and references
- OpenShift 4 course
- Kubernetes for the Absolute Beginners - Hands-on Tutorial
- Kubernetes NetworkPolicy docs: https://kubernetes.io/docs/concepts/services-networking/network-policies/