Skip to content

Service port mapping configuration

Service port mapping configuration in Kubernetes defines how network traffic is routed from an entry point to the specific containers running in Pods^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md].

The core of this configuration relies on Labels and Selectors. The Service identifies target Pods dynamically via the selector, matching labels such as type: demo^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md]. This abstraction allows the configuration to persist even if the underlying Pods are recreated or change their IP addresses.

Key Configuration Fields

The mapping behavior is defined in the spec section of a Service manifest, specifically within the ports array^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md].

  • port: This is the port number exposed on the Service's Cluster IP^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md].
  • targetPort: This specifies the port number on the Pod (or container) to which traffic is forwarded^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md]. For example, the Service might listen on port 8000 but forward traffic to port 8080 on the container^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md].
  • nodePort: Used when the Service type is NodePort or LoadBalancer, this opens a specific port on the Node's network interface^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md]. If omitted in the configuration, Kubernetes will automatically assign a random valid port number^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md].
  • protocol: Defines the network protocol for the port mapping, supporting TCP, SCTP, and UDP (defaulting to TCP)^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md].

Configuration Example

The following YAML demonstrates a LoadBalancer Service that maps external traffic from port 8000 (and NodePort 30390) to port 8080 on the selected Pods^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md].

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    type: demo
  type: LoadBalancer
  ports:
    - protocol: TCP
      port: 8000
      targetPort: 8080
      [NodePort](<./nodeport.md>): 30390

Sources

^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md]