šŸ¶
Kubernetes

Kubernetes Service port vs targetPort: What's the difference?

By Jan on 01/14/2025

This article explains the difference between targetPort and port in Kubernetes Service definition and when to use each.

Kubernetes Service port vs targetPort: What's the difference?

Table of Contents

Introduction

You have a web server nestled inside a Kubernetes pod. Within this container, your server diligently listens on a specific port, for instance, 8080. This is referred to as the targetPort. However, you need other applications to reach your web server from the outside. This is where a Kubernetes Service comes in. You create a Service and define a port, say 80, which acts as the gateway to your application. When traffic arrives at the Service on port 80, Kubernetes skillfully redirects it to one of the pods hosting your web server on port 8080.

Step-by-Step Guide

Imagine you have a web server running inside a Kubernetes pod.

  • Inside the container: Your web server listens on a specific port, let's say 8080. This is your targetPort.
ports:
- containerPort: 8080 
  • Outside the container: You want other applications to access your web server. You create a Kubernetes Service and define a port (let's say 80) that acts as the entry point.
spec:
  ports:
  - port: 80
    targetPort: 8080

Now, when traffic comes to the Service on port 80, Kubernetes redirects it to one of the pods running your web server on port 8080.

In short:

  • targetPort: The port your application listens on inside the container.
  • port: The port exposed by the Service for accessing your application from outside.

Code Example

This code demonstrates deploying a simple Flask web server on Kubernetes. It includes a Flask app that listens on port 8080, a Dockerfile to build the app image, a Kubernetes Deployment to create 3 replicas of the app, and a Kubernetes Service to expose the app on port 80 using a LoadBalancer. The app returns "Hello from Flask inside Kubernetes!" when accessed. To deploy, build and push the Docker image, then apply the deployment and service configurations. The app will be accessible through the Service's external IP address on port 80.

This example demonstrates a simple Flask web server running inside a Kubernetes pod and exposed through a Service.

1. Flask App (app.py):

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
  return "Hello from Flask inside Kubernetes!"

if __name__ == "__main__":
  app.run(host='0.0.0.0', port=8080)

2. Dockerfile:

FROM python:3.9-slim-buster

WORKDIR /app

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . .

CMD ["python", "app.py"]

3. Kubernetes Deployment (deployment.yaml):

apiVersion: apps/v1
kind: Deployment
metadata:
  name: flask-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: flask-app
  template:
    metadata:
      labels:
        app: flask-app
    spec:
      containers:
      - name: flask-container
        image: <your-docker-image>
        ports:
        - containerPort: 8080

4. Kubernetes Service (service.yaml):

apiVersion: v1
kind: Service
metadata:
  name: flask-service
spec:
  selector:
    app: flask-app
  ports:
  - port: 80
    targetPort: 8080
  type: LoadBalancer

Explanation:

  • app.py: This is our simple Flask app listening on port 8080 inside the container.
  • Dockerfile: This builds a Docker image containing our Flask app and its dependencies.
  • deployment.yaml: This defines a Kubernetes Deployment that creates 3 replicas of our Flask app pods.
  • service.yaml: This defines a Kubernetes Service that exposes our Flask app on port 80. It uses targetPort: 8080 to redirect traffic to the correct port inside the pods. The type: LoadBalancer will provision a load balancer (if your cloud provider supports it) to distribute traffic across the pods.

Deployment:

  1. Build and push your Docker image: docker build -t <your-docker-image> . and docker push <your-docker-image>
  2. Apply the Kubernetes configurations: kubectl apply -f deployment.yaml and kubectl apply -f service.yaml

Now, you can access your Flask app through the external IP address assigned to the Service on port 80.

Additional Notes

  • Service Abstraction: Kubernetes Services provide a stable endpoint (DNS name and IP address) to access your application, even if the underlying pods are dynamic (e.g., scaling, failures, updates).
  • Load Balancing: Services distribute incoming traffic across multiple pods running your application, providing high availability and scalability.
  • Service Discovery: Services act as a registry for your applications, allowing other services within the cluster to easily discover and communicate with each other.
  • Port Flexibility: You can map different port values in the Service to the same targetPort on the pods, allowing for flexibility in how clients access your application.
  • Other Service Types: Besides LoadBalancer, Kubernetes offers other Service types like ClusterIP (internal access within the cluster) and NodePort (exposing the service on a static port on each node).
  • Health Checks: Services can perform health checks on your pods to ensure only healthy instances receive traffic.
  • Namespaces: Services are scoped to a specific namespace. If omitted, they default to the default namespace.
  • YAML Best Practices: Use clear and descriptive names for your Services and deployments. Indentation and formatting are crucial for readability in YAML files.

Security Considerations:

  • Ingress Controllers: For external access, consider using an Ingress controller along with your Service for more advanced routing, SSL termination, and security features.
  • Network Policies: Implement Network Policies to control traffic flow between pods and Services, enhancing security within your cluster.

Troubleshooting:

  • kubectl get services: Use this command to check the status of your Service and its external IP (if applicable).
  • kubectl describe service <service-name>: Get detailed information about your Service, including its endpoints and events.
  • Logs: Examine the logs of your pods and the Kubernetes control plane for any errors or issues related to your Service.

Summary

Term Description Location
targetPort The port your application inside the container listens on. Defined in the container's configuration.
port The external port exposed by the Kubernetes Service for accessing the application. Defined in the Service's configuration.

Summary:

Kubernetes Services act as a bridge between external traffic and your application running inside a pod. The targetPort specifies the port your application listens on within the container, while the port defines the external port exposed by the Service. When traffic reaches the Service on the defined port, Kubernetes redirects it to one of the pods running your application on the specified targetPort.

Conclusion

Kubernetes Services are essential for making applications running inside pods accessible within and outside a cluster. They provide a stable entry point (port) to reach your application, regardless of which pod is currently running it. The Service routes traffic to the correct port (targetPort) on the pods, abstracting away the complexities of pod management. This separation of concerns simplifies application deployment and management, making Kubernetes a powerful platform for running scalable and resilient applications. Understanding the relationship between port and targetPort is crucial for configuring Services effectively and ensuring seamless communication between your applications in a Kubernetes environment.

References

Were You Able to Follow the Instructions?

šŸ˜Love it!
šŸ˜ŠYes
šŸ˜Meh-gical
šŸ˜žNo
šŸ¤®Clickbait