Skip to content

Port mapping in Kubernetes Services

Port mapping in Kubernetes Services defines how traffic is routed between external clients, the Service's virtual IP, and the containerized applications running in Pods^[400-devops-06-kubernetes-k8s-learning-05service-service.md].

Configuration Parameters

Port mapping is defined using two key parameters when exposing a Deployment:

  • --port: The port number exposed by the Service itself. This is the port that other services or clients use to connect^[400-devops-06-kubernetes-k8s-learning-05service-service.md].
  • --target-port: The port number on the Pod (container) where the application is listening^[400-devops-06-kubernetes-k8s-learning-05service-service.md].

For example, to access a web application running on port 80 inside the Pods via port 8000 on the Service, you would use kubectl expose deploy nginx-deployment --port=8000 --target-port=80^[400-devops-06-kubernetes-k8s-learning-05service-service.md].

Service Types and Access

The behavior of port mapping depends on the type of Service created.

ClusterIP

By default, creating a Service generates a ClusterIP, assigning a virtual IP (e.g., 10.96.87.175) accessible only within the cluster^[400-devops-06-kubernetes-k8s-learning-05service-service.md]. Traffic sent to the Service IP on the specified --port is load-balanced across the backend Pods to the --target-port^[400-devops-06-kubernetes-k8s-learning-05service-service.md].

NodePort

When creating a Service with --type=NodePort, Kubernetes exposes the Service on each Node's IP at a static port (the NodePort)^[400-devops-06-kubernetes-k8s-learning-05service-service.md]. In this scenario, the mapping expands to three components: <NodeIP>:<NodePort> -> ServiceIP:<ServicePort> -> PodIP:<TargetPort>^[400-devops-06-kubernetes-k8s-learning-05service-service.md].

For instance, a configuration of --port=8000 --target-port=80 might result in a NodePort mapping of 8000:30427/TCP, allowing external access via curl <NodeIP>:30427^[400-devops-06-kubernetes-k8s-learning-05service-service.md].

Internal Discovery

Within the cluster, applications can reach the Service using standard DNS resolution and the Service port, without needing to know the Pod IPs^[400-devops-06-kubernetes-k8s-learning-05service-service.md]. This works via the syntax service-name:port or service-name.namespace.svc:port^[400-devops-06-kubernetes-k8s-learning-05service-service.md].

Sources

  • 400-devops-06-kubernetes-k8s-learning-05service-service.md
  • Kubernetes
  • [[Load balancing]]
  • [[Container networking]]