content_image/869962.jpg content_image/869961.jpg content_image/869960.jpg
ports : - port : 80 targetPort : 8080 protocol : TCP 

Selector matching Pod labels 

<img src='content_image/869962.jpg'>

Port over which this Service can be contacted 

Port on which the Pods are listening 

<img src='content_image/869961.jpg'>

The definition in this example will create a Service named random-generator  (the name is important for discovery later) and type: ClusterIP  (which is the default) that accepts TCP connections on port 80 and routes them to port 8080 on all the matching Pods with selector app: random-generator . It doesn’t matter when or how the Pods are created—any matching Pod becomes a routing target, as illustrated in Figure 12-3. 

<img src='content_image/869960.jpg'>

The essential points to remember here are that once a Service is created, it gets a clus terIP  assigned that is accessible only from within the Kubernetes cluster (hence the name), and that IP remains unchanged as long as the Service definition exists. How‐ ever, how can other applications within the cluster figure out what this dynamically allocated clusterIP  is? There are two ways: 

Discovery through environment variables 

When Kubernetes starts a Pod, its environment variables get populated with the details of all Services that exist up to that moment. For example, our random- generator  Service listening on port 80 gets injected into any newly starting Pod, as the environment variables shown in Example 12-2 demonstrate. The applica‐ tion running that Pod would know the name of the Service it needs to consume, and can be coded to read these environment variables. This lookup is a simple 

