> For the complete documentation index, see [llms.txt](https://notes.nomanaziz.me/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://notes.nomanaziz.me/devops/orchestration/kubernetes/10.-k8-services.md).

# 10. K8 Services

### Service

* Each pod has its own IP address
  * Pods are ephemeral - destoryed frequently
* Service gives stable IP address
* Provides load balancing

***

### Types

#### 1. ClusterIP

* default type
* pod gets ip address from node's range

**How Service Knows which Pod to Forward Request to**

<figure><img src="/files/6IwOcSwpVHDfagY29Kif" alt=""><figcaption></figcaption></figure>

**How Service Knows which Port to Forward Request to**

<figure><img src="/files/kcc9jJjuH9Rt74OgaDWg" alt=""><figcaption></figcaption></figure>

**Service Endpoints**

* K8 create endpoints object
* have same name as service
* keeps track of which pods are members/endpoint of the service

**Multiple Ports Service**

<figure><img src="/files/Cyk4uNZxDh03fygWsgoZ" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/XUbZ2zSNI0RWYLGtrJQM" alt=""><figcaption></figcaption></figure>

#### 2. Headless Service

* clients want to communicate with 1 specific pod directly
* pod wants to talk directly with specific pod not a randomly selected pod
* Use Case: Stateful applications like databases
  * pod replicas are not identical
* Client needs to figure out IP address of each pod
  * Option 1 - API call to K8 API Server (X)
  * Option 2 - DNS Lookup (Recommended)

    * DNS lookup for service - returns single ip address
    * If ClusterIP is set to None - returns pod ip address instead
    *

    ```
    <figure><img src="/files/rwCz5twrObfttc5vbkY1" alt=""><figcaption></figcaption></figure>
    ```

***

### Service Type Attributes

1. ClusterIP
   * Only accessible within cluster
2. NodePort

   * extension of clusterip service
   * External traffic has access to fixed port on each worker node
   *

   ```
   <figure><img src="/files/E2ztPvAaIe7P4huyIZy2" alt=""><figcaption></figcaption></figure>
   ```

   *

   ```
   <figure><img src="/files/FBDgiXWTayvGEDeW8BVr" alt=""><figcaption></figcaption></figure>
   ```

   * not secure and efficient since port is directly accessible externally
   * not used in production environments
3. Load Balancer

   * extension of nodeport service
   * becomes accessible externally through cloud provider loadbalancers
   *

   ```
   <figure><img src="/files/5Tuv3KilYtQct3MqYGpk" alt=""><figcaption></figcaption></figure>
   ```

   * secure and efficient since port is not accessible directly but via load balancer
   * used in production environments

***
