Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 63

Exposing Services with Kubernetes YAML

This lesson is built with resources from youtube.com, learnkube.com and 1 more site.

Hello! Welcome back to the course.

In our last lesson, we successfully deployed our Blog service to the EKS cluster using a Deployment manifest. We now have two running Pods, but they are isolated islands. Their internal IP addresses are ephemeral, meaning they can change at any time, making them unreliable for communication. We can't connect to them from the outside world, or even from other services within the cluster.

Today, we'll solve this problem by creating a Kubernetes Service. A Service provides a stable, internal network endpoint that will group our blog service Pods and load-balance traffic between them. This is the crucial next step to making our application accessible and resilient.

MERN Stack Comparison

In a Node.js/Express environment, you typically run a single process on a specific port. If you scale your application using a process manager like PM2 in cluster mode, you suddenly have multiple processes, each with its own internal endpoint. To manage this, you'd place a reverse proxy like Nginx in front of them to provide a single, stable entry point and to load balance requests.

A Kubernetes Service plays a very similar role to that Nginx reverse proxy, but it operates natively within the Kubernetes network. It's an internal load balancer that discovers and routes traffic to a set of backend Pods.



1. Why Do We Need a Service?

The core problem a Service solves is the transient nature of Pods. As you know from the previous lesson, a Deployment can create, destroy, and reschedule Pods at any time. Each new Pod gets a new internal IP address.

This creates a challenge:

  • How does our future API Gateway find and send requests to the Blog service if the Pod IPs are always changing?
  • If we have multiple replicas of the Blog service, which one should the Gateway talk to?

A Service provides the solution.

Kubernetes Services explained | ClusterIP vs NodePort vs LoadBalancer vs Headless Service

To understand the core problem that Services solve, watch this introductory clip from the "Kubernetes Services explained" video by TechWorld with Nana. It clearly explains why you can't rely on Pod IP addresses.

Watch from 00:33 to 02:14. Focus on the concepts of ephemeral Pods and how a Service provides a stable IP address and load balancing.

As the video explains, a Service gives us a stable IP address and a DNS name that remains constant, even as the Pods behind it come and go.



2. How a Service Finds its Pods

A Service and a Deployment are not directly linked. Instead, a Service finds the Pods it should send traffic to using labels and selectors. This is the same mechanism the Deployment uses to know which Pods it manages.

Here are the two critical connections you must configure:

  1. Selector to Label Match: The Service has a selector field. It continuously scans for Pods that have labels matching this selector. Your Deployment's Pod template must have these exact labels.
  2. Port Mapping: The Service needs to know which port on the Pod to forward traffic to.
    • targetPort: This is the port your application container is listening on. For our Spring Boot app, this is 8080, which we defined as the containerPort in our Deployment.
    • port: This is the port that the Service itself exposes inside the cluster. Other services will communicate with this Service on this port. It's common to use standard ports like 80 for HTTP.

Connecting Deployment and Service

This article, "A visual guide on troubleshooting Kubernetes deployments", has excellent diagrams that illustrate this relationship. It's the best way to visualize how the different YAML files connect.

Read the sections "Connecting Deployment and Service" and "Recap on ports". Pay close attention to the diagrams showing how the Service's selector must match the Pod's label, and how the Service's targetPort must match the container's containerPort.

This decoupling is powerful. It means you could have multiple Deployments (e.g., for different versions of your app) managed by a single Service, as long as their Pods share the same label.



3. Types of Services

Kubernetes offers several types of Services, each for a different use case. We'll focus on ClusterIP today, as it's the foundation for all internal communication.

  • ClusterIP (Default): Exposes the Service on an IP address that is only reachable from within the cluster. This is perfect for backend services like our blog-service that shouldn't be exposed directly to the internet but need to be reached by other components like an API Gateway.

  • NodePort: Exposes the Service on a static port on each worker node's IP address. This makes the service accessible from outside the cluster, which is useful for development or debugging, but it's not a secure or scalable way to expose production applications.

  • LoadBalancer: Exposes the Service externally using a cloud provider's load balancer (e.g., an AWS Elastic Load Balancer). When you create a LoadBalancer Service, AWS will automatically provision an ELB and configure it to route traffic to your Service's NodePort. This is the standard way to expose services to the internet. We will use this for our API Gateway in a later module.

Kubernetes Services explained | ClusterIP vs NodePort vs LoadBalancer vs Headless Service

To see how a ClusterIP service works in detail, let's return to the video from TechWorld with Nana.

Watch from 02:14 to 12:52. This is a deep dive into the ClusterIP service type. Focus on understanding how it provides an internal endpoint for other services (like an Ingress or another microservice) to connect to.



4. Hands-On: Creating the Blog Service's Service

Let's create a ClusterIP Service to expose our blog-service-deployment.

Step 1: Create the Manifest File

In your kube directory, create a new file named blog-service-service.yaml.

/blog-platform
|-- /kube
|   |-- blog-service-deployment.yaml
|   |-- blog-service-service.yaml  <-- NEW FILE
|-- /src
|-- ...

Step 2: Write the Service Manifest

Copy the following YAML into blog-service-service.yaml.




# kube/blog-service-service.yaml
apiVersion: v1
kind: Service
metadata:
  name: blog-service
spec:
  type: ClusterIP
  selector:
    app: blog-service
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080

Let's break this down with a visual guide.

Kubernetes Service YAML Manifest with NodePort Type
This annotated image shows a similar Service manifest. In our case: `selector` is `app: blog-service` to match our Pods. `port` is `80`, the port other services will use to call this one. `targetPort` is `8080`, the port our Spring Boot application is listening on inside the container.

Step 3: Apply the Manifest and Verify

Now, let's apply this configuration to our EKS cluster and see the magic happen.

  1. Apply the configuration:

    kubectl apply -f kube/blog-service-service.yaml
    

    You should see service/blog-service created.

  2. Verify the Service: Check that the Service object was created.

    kubectl get service blog-service
    

    You'll see output like this. Note the CLUSTER-IP, which is the stable internal IP address for our service.

    NAME           TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
    blog-service   ClusterIP   10.100.17.151   <none>        80/TCP    25s
    
  3. Inspect the Endpoints: This is the most important verification step. It confirms that the Service has found our Pods.

    kubectl describe service blog-service
    

    Look for the Endpoints line in the output. It should list the internal IP addresses of the two Pods created by your Deployment.

    Name:              blog-service
    Namespace:         default
    Labels:            <none>
    Annotations:       <none>
    Selector:          app=blog-service
    Type:              ClusterIP
    IP Family Policy:  SingleStack
    IP Families:       IPv4
    IP:                10.100.17.151
    IPs:               10.100.17.151
    Port:              <unset>  80/TCP
    TargetPort:        8080/TCP
    Endpoints:         192.168.1.10:8080,192.168.2.25:8080  <-- BINGO!
    Session Affinity:  None
    Events:            <none>
    

    If you see IPs listed under Endpoints, your Service is correctly configured and routing traffic.



5. Debugging-First: Service Issues

What if the Endpoints list is empty? This is a very common issue.

Troubleshooting Services

The visual guide we looked at earlier also has a fantastic section on troubleshooting services. Let's walk through its debugging steps.

Read the section titled "2. Troubleshooting Services". Focus on the two primary causes of failure: an empty Endpoints section (label mismatch) and an incorrect targetPort.

As the guide explains, here's your debugging workflow:

Problem: Endpoints section is empty.

  • Cause: The Service's selector does not match the labels on any running Pods.
  • Fix:
    1. Run kubectl describe service blog-service and note the Selector.
    2. Run kubectl get pods --show-labels and look at the labels for your blog-service-deployment-xxxx pods.
    3. Compare them. A typo is the most common culprit. Correct the YAML in either the Deployment or the Service and kubectl apply it again.

Problem: Endpoints exist, but you still can't connect.

  • Cause: The Service's targetPort might be wrong. The Service is sending traffic to a port on the Pod where nothing is listening.
  • Fix:
    1. Check the targetPort in blog-service-service.yaml (it should be 8080).
    2. Check the containerPort in blog-service-deployment.yaml (it should also be 8080).
    3. Verify your application is actually running on that port by checking its logs (kubectl logs <pod-name>).

You can also test the full path from the Service to the Pods using port-forwarding:




# Forward a local port (e.g., 9090) to the Service's port (80)
kubectl port-forward service/blog-service 9090:80

Now, open a new terminal and run curl http://localhost:9090. If you get a response, you've confirmed the entire chain from Service-to-Pod is working correctly.



Conclusion

Excellent work! You've successfully created a stable network abstraction for your backend application. Our blog-service is now properly exposed within the cluster, ready to receive traffic from other services.

Key Takeaways:

  • A Kubernetes Service provides a stable IP address and DNS name for a group of ephemeral Pods.
  • The connection between a Service and its Pods is made with labels and selectors.
  • The port is the Service's internal port, while the targetPort is the port on the container.
  • The ClusterIP service type is for internal-only communication.
  • To debug a Service, always start with kubectl describe to check the Selector and Endpoints.

Preview of the Next Lesson:
We've now set up a Deployment and a Service for our Blog service. The next logical step is to do the same for our other microservices: the Auth service and the API Gateway. In the next lesson, you will apply what you've learned to write the Deployment and Service manifests for these remaining components.