Confusion on Services

Hi All - Need some guidance.

I have a redis pod which is open on 6379 port. I created a ClusterIP type service. Just to play with the different possibilities, i did not give any target port in the service. And I gave the port as 6380. However, when i describe the service, i see that the target port is being set to 6380 as well. I am a little confused on how the target port gets the port? I was expecting the port to be set based on the open port of the endpoint.

Following is the manifest that i have used and the corresponding describe output of the service:

apiVersion: v1
kind: Service
metadata:
name: data-tier-svc
labels:
app: microservices
spec:
ports:

  • port: 6380
    protocol: TCP # default
    name: redis-port # optional when only 1 port
    selector:
    tier: data-pod-label
    type: ClusterIP # default

apiVersion: apps/v1 # apps API group
kind: Deployment
metadata:
name: data-deploy
labels:
app: microservices
tier: data-deploy-label
spec:
replicas: 1
selector:
matchLabels:
tier: data-pod-label
template:
metadata:
labels:
app: microservices
tier: data-pod-label
spec: # Pod spec
containers:
- name: redis-c
image: redis:latest
imagePullPolicy: IfNotPresent
ports:
- containerPort: 6379

kubectl describe svc data-tier-svc
Name: data-tier-svc
Namespace: default
Labels: app=microservices
Annotations:
Selector: tier=data-pod-label
Type: ClusterIP
IP Families:
IP: 10.96.211.202
IPs: 10.96.211.202
Port: redis-port 6380/TCP
TargetPort: 6380/TCP
Endpoints: 192.168.23.132:6380
Session Affinity: None
Events:

Does this mean,

  1. If the service port number and the container port number are same, the target port in the service (if not specified) will be set to the same port number.
  2. If the service port number and the container port number are different, the target port in the service has to be set explicitly (to the same port number of the container) else this communication will not work.

https://kubernetes.io/docs/concepts/services-networking/service/

By default and for convenience, the `targetPort` is set to the same value as the `port` field.
nodePort:  Optional field
 By default and for convenience, the Kubernetes control plane will allocate a port from a range (default: 30000-32767)

@kamil-dolmatov Thanks again. More reading required. :slight_smile: