NetworkPolicy: Why are pod selectors used over "service selectors"? My understanding of containers is that they should be considered to be short-lived. In addition, we can scale containers (and if using a container orchestrator like k8s, via pods) by creating additional instances on one or more machines.
In order to allow for the ephemeral nature of containers, as well as to allow users to access an application from only one address (say, www.myapp.com), we must abstract away the container. From now on, I'm going to assume we're using k8s as the container orchestrator and speak only of pods. In k8s, we do this by using Services to expose pods (either to other pods which comprise the application, or directly to users). Services allow us to load balance and allow for deployment scenarios such as blue/green and zero-downtime deployments while providing a consistent and abstract interface from which to access the underlying pods.
With this in mind, I have a question about the NetworkPolicy resource in k8s. When creating a NetworkPolicy, a podSelector is used to determine to which pod(s) a network policy applies. However, since a Service must be created in order to expose a pod, why is it, then, that a NetworkPolicy uses a podSelector instead of a &quot;serviceSelector&quot;? Wouldn't the concept of a &quot;serviceSelector&quot; be more general/abstract, and better reflect to what the policy is really allowing access? Is there a reason I'm unaware of for why network policies are &quot;applied&quot; to pods versus services? (Not to say that you would never want a NetworkPolicy to apply directly to a pod, but, generally speaking, most times we apply them to pods which are exposed by a Service—or maybe I'm totally off base here?)
Pods is the deployment unit in Kubernetes and it is also the unit that gets a single unique IP address within the cluster.
You can access Pods without going via a Service. A Service is mostly there to get a &quot;stable&quot; address for an application, where the traffic is then load balanced to any Pod representing the Service. Both Pods and Services gets a DNS name in the cluster.
A Service has a selector to identify what Pods belong to the Service, but a Pod can receive traffic from multiple Services. In the same way a NetworkPolicy has a selector to select the Pods where it is applied.
Since a Pod is the smallest unit in Kubernetes, that gets its own unique network address it also makes sense to add the network security (e.g. Network Policies) at this level.